开发者

Proper use of for loops in Matlab

for ii=1:size(K) 
  Xsol(ii) =  (K(ii) - average/2) ; 
  Xsag(ii) =  (K(ii) + average/2) ;
end

I get the following output:

Xsol =

    5.5000

Xsag =

   36.5000 

But it could be like that Xsol(1) and X开发者_如何学Csol(2). How could I get this?


If K is a 1 x N matrix, then size(K) yields [1 N]. When you use it your for loop, it does not work because it is not a scalar (actually, and quite painfully, Matlab simply uses the first element to limit the loop, and does not even issue a warning). Instead, write:

for ii=1:numel(K) 
  Xsol(ii) =  (K(ii) - average/2) ; 
  Xsag(ii) =  (K(ii) + average/2) ;
end

The function numel returns a scalar, i.e., the total number of elements.

However, as pointed out by @Jonas, you do not need a loop in this case. In general, loops are extremely slow as compared to array operations.


Instead of performing the calculation inside a loop, you can also call

Xsol = K - average/2;
Xsag = K + average/2;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜