create a 2d matrix making sure that the second column from the left and second column from the right are equal to the column number in matlab

main.m
% define matrix size
n_rows = 5; % number of rows
n_cols = 4; % number of columns

% initialize matrix with zeros
matrix = zeros(n_rows, n_cols);

% populate matrix
for i = 1:n_rows
    for j = 1:n_cols
        % check if current column is second from the left or right
        if (j == 2) || (j == n_cols - 1)
            % set current element to the column index
            matrix(i,j) = j;
        end
    end
end

% display matrix
disp(matrix);
450 chars
21 lines

The above code creates a 2D matrix in Matlab, where the second column from the left and the second column from the right are equal to the column number. It does this by creating an empty matrix of zeros, and then looping through each element in the matrix. For each element, it checks if the column index is equal to 2 or n_cols - 1 (second column from the right). If it is, it sets the current element to the column index. Finally, it displays the resulting matrix.

gistlibby LogSnag