for or while loops in matlab

喜欢而已 提交于 2019-12-01 23:37:52

The command bsxfun is very helpful for such problems. It will do all the looping and preallocation for you.

eg:

bsxfun(@(x,y) x.^y./(x+y), (1:3)', 1:5)
Dan

Since you need to know the row and column numbers (and only because you have to use loops), for-loops are a natural choice. This is because a for-loop will automatically keep track of your row and column number for you if you set it up right. More specifically, you want a nested for loop, i.e. one for loop within another. The outer loop might loop through the rows and the inner loop through the columns for example.

As for starting new lines in a matrix, this is extremely bad practice to do in a loop. You should rather pre-allocate your matrix. This will have a major performance impact on your code. Pre-allocation is most commonly done using the zeros function.

e.g.

num_rows = 3;
num_cols = 5;
M = zeros(num_rows,num_cols); %// Preallocation of memory so you don't grow your matrix in your loop
for row = 1:num_rows
    for col = 1:num_cols
        M(row,col) = (row^col)/(row+col);
    end
end

But the most efficient way to do it is probably not to use loops at all but do it in one shot using ndgrid:

[R, C] =  ndgrid(1:num_rows, 1:num_cols);
M = (R.^C)./(R+C);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!