In: Computer Science
Write a MATLAB script which gets a matrix as input and check the dimensions of the input:
Part A) If the input matrix is a square matrix, calculate the inverse of it and show it in the command window, otherwise, show the text “the input matrix is not invertible”.
Part B) Reshape the input matrix to a row vector and assign it to Y and make a vector named X with the same length as Y then make a 2D Plot and show it.
% Solution to part A
% Take an input matrix from the user
mat = input("Please enter an input matrix");
% Get the dimensions of input matrix
[rows,cols] = size(mat);
% check if the input matrix is a square matrix
% for square matrix no_of_rows = no_of_columns
if(rows ~= cols) % if no_of_rows is not equal to no_of_columns, so not a square matrix
disp("the input matrix is not invertible"); % display message that matrix is not invertible
else
% calculate inverse of matrix
matInv = inv(mat);
disp("The inverse of entered matrix is: ");
disp(matInv); % Display the inverse of matrix in command window
end
% Part B begins from here
% Reshape the matrix into a row vector
% A row vector has only one row and may have any number of columns
% Eg [1 2 3 4 5 7 2 3 4], [1 67 89 34] etc
Y = reshape(mat,1,[]); % using 1 as second argument tells that no of rows in
% resultant should be 1 and [] as third argument tells
% system to calculate number of columns itself. You can find more information by
% typing 'doc reshape' into the command window.
X = 1:length(Y); % Create a row vector X with values 1 to length of Y.
% Eg if Y=[10 20 30 32 45] then X = [1 2 3 4 5]
% Create a 2D plot
plot(X,Y,"r*"); % creates a 2D plot with red coloured stars and no lines
% Use the below command if you wish to display lines as well
%plot(X,Y,"r*-");
% You may optionally add labels to X axis and Y axis with below commands
% xlabel("Enteries in X vector");
% ylabel("Enteries in Y vector");
------------------------------------------------------------------------------------
OUTPUTS
------------------------------------------------------------------------------------
Plot for the same
Another example with a non square matrix as input
Plot for above