create a simple program that can multiply two matrices in matlab. let the user input the elements in matrices. in matlab

To create a simple program that multiplies two matrices in MATLAB and allows the user to input the elements, you can follow these steps:

  1. Prompt the user to enter the dimensions of the matrices and create empty matrices based on those dimensions.
main.m
rows_A = input('Enter the number of rows for matrix A: ');
cols_A = input('Enter the number of columns for matrix A: ');
A = zeros(rows_A, cols_A);

rows_B = input('Enter the number of rows for matrix B: ');
cols_B = input('Enter the number of columns for matrix B: ');
B = zeros(rows_B, cols_B);
297 chars
8 lines
  1. Ask the user to input the elements for each matrix using nested loops.
main.m
disp('Enter the elements for matrix A:');
for i = 1:rows_A
    for j = 1:cols_A
        A(i, j) = input(sprintf('Enter the element at position (%d, %d): ', i, j));
    end
end

disp('Enter the elements for matrix B:');
for i = 1:rows_B
    for j = 1:cols_B
        B(i, j) = input(sprintf('Enter the element at position (%d, %d): ', i, j));
    end
end
353 chars
14 lines
  1. Check if the dimensions of the matrices are compatible for matrix multiplication (the number of columns in matrix A should be equal to the number of rows in matrix B). If not, show an error message and terminate the program.
main.m
if cols_A ~= rows_B
    disp('Error: The number of columns in matrix A should be equal to the number of rows in matrix B.');
    return; % Terminate the program
end
165 chars
5 lines
  1. Multiply the two matrices using the * operator and store the result in a new matrix C.
main.m
C = A * B;
11 chars
2 lines
  1. Display the resulting matrix C.
main.m
disp('Resulting matrix C:');
disp(C);
38 chars
3 lines

Putting it all together in a MATLAB script, the complete example would be:

main.m
rows_A = input('Enter the number of rows for matrix A: ');
cols_A = input('Enter the number of columns for matrix A: ');
A = zeros(rows_A, cols_A);

rows_B = input('Enter the number of rows for matrix B: ');
cols_B = input('Enter the number of columns for matrix B: ');
B = zeros(rows_B, cols_B);

disp('Enter the elements for matrix A:');
for i = 1:rows_A
    for j = 1:cols_A
        A(i, j) = input(sprintf('Enter the element at position (%d, %d): ', i, j));
    end
end

disp('Enter the elements for matrix B:');
for i = 1:rows_B
    for j = 1:cols_B
        B(i, j) = input(sprintf('Enter the element at position (%d, %d): ', i, j));
    end
end

if cols_A ~= rows_B
    disp('Error: The number of columns in matrix A should be equal to the number of rows in matrix B.');
    return; % Terminate the program
end

C = A * B;

disp('Resulting matrix C:');
disp(C);
868 chars
32 lines

Hope this helps!

related categories

gistlibby LogSnag