3
votes

Is it possible in Matlab to use only matrix operations in order to create a NxN matrix Mat like the following two foor loops would do?

Mat = zeros(N);
for row = 1:N
    for col = 1:N
        if (row == 1 && (1 <= col && col <= N))
            Mat(row,col) = N;
        end
        if ((2 <= row && row <= N) && (1 <= col && col <= N))
            Mat(row,col) = (2*row+1)*col;
        end
    end
end

I thought indexing the corresponding rows and columns like:

Mat(1,1:N) = N;

row = 2:N;
col = 1:N;
Mat(row,col) = (2.*row+1).*col;

The first line is working. But the second operation leads obviously to a problem with the dimensions of row and col.

How can I use each value of row and col? Or is there a simpler way of achieving the same result from the two foor loops?

3

3 Answers

3
votes

You could also use ndgrid;

[II,JJ] = ndgrid(1:N);
Mat = JJ+2*JJ.*II;
Mat(1,:) = N;
3
votes

For the first if statement (if (row == 1 && (1 <= col && col <= N))) you're essentially saying "set every element in the first row to N". This is easily achieved using:

Mat(1,:) = N;

where the first argument in the brackets tells matlab to select the first row, and the second argument tells it to select every element in that row.

The second if statement is a little bit more complicated, but still doable. Now we're saying "for every row other than the first row, set each element Mat(row,column) to (2*row+1)*col". This is easily accomplished using bsxfun:

row = 2:N;
col = 1:N;
Mat(2:end,:) = bsxfun(@times,2.*row' + 1, col);
1
votes
Mat = [ repmat(N,1,N); (2*repmat((2:N).',1,N)+1) .* repmat(1:N,N-1,1) ];