d Consider the case where the input to a program can be eith

d) Consider the case where the input to a program can be either a scalar, vector, a matrix or a combination of these. Write a program that can add, subtract, multiply or divide the input variables. Note that the division portion is not valid for matrices we use inverses instead) you will need to incorporate this in your code. Your program should prompt the user for the type of operation to be performed, to enter error message using fprint) or the ap if the code fails to execute. Test your code using at least 7 different combinations of x and y, allowing each to be scalars, matrices of various shapes (not only square) and vectors.

Solution

MATLAB CODE :

clc;
clear all;
str=input(\'Type of Operation(add,sub,mul,div) :\',\'s\'); % takes input operation as string type
x=input(\'Enter first variable : \'); % variables in scalar , vector and matrix
y=input(\'Enter second variable : \');
r=0; %intializing result

add_num= strcmp(\'add\',str); % if string comparision true it returns \'1\' else \'0\'
sub_num = strcmp(\'sub\',str);
mul_num= strcmp(\'mul\',str);
div_num= strcmp(\'div\',str);


if add_num==1 %compares wheather add is typed
r=x+y; %addition
fprintf(\'Result = %4.2f\',r); %prints results in 2 decimal places

else if sub_num==1
r=x-y;
fprintf(\'Result = %4.2f\',r);

else if mul_num ==1
[rowy, coly] = size(y); % determines rows and columns
[rowx, colx] = size(x);
if colx==rowy % checks condition for matrix multplication
r=x*y;
else fprintf(\'Error--- columns of 1st match rows of 2nd\');
end
  
fprintf([repmat(\'%4.2f\\t\', 1, size(r, 2)) \'\ \'], r\'); % prints result as matrix
else if div_num==1
[rowy, coly] = size(y);
[rowx, colx] = size(x);
if colx==rowy
else if rowy==coly
r=x/y;
  
else fprintf(\'Error ---division requires square matrix\');
  
end
end
  
fprintf([repmat(\'%4.2f\\t\', 1, size(r, 2)) \'\ \'], r\');
  

end
end
end
end
  



  

 d) Consider the case where the input to a program can be either a scalar, vector, a matrix or a combination of these. Write a program that can add, subtract, m
 d) Consider the case where the input to a program can be either a scalar, vector, a matrix or a combination of these. Write a program that can add, subtract, m

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site