create a simple program that can add and subtract two matrices a and b. let the user input the elements in matrices. in matlab

Here is a simple program in MATLAB that allows the user to input elements for two matrices A and B, and perform addition and subtraction between them:

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

% User inputs for matrix B
rows_B = input('Enter the number of rows for matrix B: ');
cols_B = input('Enter the number of columns for matrix B: ');

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

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

% Addition
if rows_A == rows_B && cols_A == cols_B
    addition_result = A + B;
else
    disp('Error: Matrices A and B should have the same dimensions for addition.');
end

% Subtraction
if rows_A == rows_B && cols_A == cols_B
    subtraction_result = A - B;
else
    disp('Error: Matrices A and B should have the same dimensions for subtraction.');
end

% Display results
disp('Addition result:');
disp(addition_result);

disp('Subtraction result:');
disp(subtraction_result);
1202 chars
47 lines

In this program, the user first enters the number of rows and columns for both matrices A and B. Then, the program prompts the user to input the elements for each matrix. After that, it performs addition and subtraction between the two matrices by checking if they have the same dimensions. Finally, it displays the addition and subtraction results.

gistlibby LogSnag