create a for loop for a matrix of any size that asks for rows and column where the first row is one and the last row is 0 in matlab in matlab

Here is an example code for creating a for loop for a matrix of any size that asks for rows and columns where the first row is one and the last row is zero and fills the matrix with incremented values:

main.m
% ask user for number of rows and columns
rows = input("Enter number of rows: ");
cols = input("Enter number of columns: ");

% create a matrix of zeros with given dimensions
matrix = zeros(rows, cols);

% fill the matrix with incremented values
for i = 1:rows
    for j = 1:cols
        if i == 1
            matrix(i,j) = j;
        elseif i == rows
            matrix(i,j) = 0;
        else
            matrix(i,j) = matrix(i-1,j) + 1;
        end
    end
end

% display the matrix
disp(matrix);
499 chars
23 lines

To test the code, you can run it in the MATLAB command window and provide the number of rows and columns when prompted. The output will be a matrix with the specified requirements.

gistlibby LogSnag