Matlab: using matrix operations instead of for loops

我只是一个虾纸丫 提交于 2019-12-22 10:03:02

问题


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?


回答1:


You could also use ndgrid;

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



回答2:


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);



回答3:


Mat = [ repmat(N,1,N); (2*repmat((2:N).',1,N)+1) .* repmat(1:N,N-1,1) ];


来源:https://stackoverflow.com/questions/20388440/matlab-using-matrix-operations-instead-of-for-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!