way to avoid for loops

What is the best way to write the following code without using any kind of loop?
N=2;
[x,y]=meshgrid(1:N,1:N);
s=zeros(N);
for i=1:N
for j=1:N
s(i,j)=sum(sum(i*x+j*y));
end
end
Some more: What if I make the function a little complex like below?
N=2;
[x,y]=meshgrid(1:N,1:N);
s=zeros(N);
for i=1:N
for j=1:N
s(i,j)=sum(sum(exp(sqrt((x-i).^2+(y-j).^2));
end
end

回答 (2 件)

Roger Stafford
Roger Stafford 2016 年 6 月 14 日
編集済み: Roger Stafford 2016 年 6 月 14 日

2 投票

If x and y are arbitrarily defined as N-by-N arrays, do this:
[I,J] = ndgrid(1:N);
s = sum(x(:))*I+sum(y(:))*J;
With x and y as you defined them, do this:
s = N^2*(N+1)/2*(x+y);

1 件のコメント

Rahul Shaw
Rahul Shaw 2016 年 6 月 15 日
Thanks for your reply but my problem is little more complicated than this. I have updated the question accordingly.

サインインしてコメントする。

Roger Stafford
Roger Stafford 2016 年 6 月 15 日

0 投票

This is for your revised problem involving the 'exp' function. (Note: I am assuming the x and y in your code are just as you have written them and not a general x and y.)
N = 10 % <-- You choose N
[I,J] = meshgrid(-N+1:N-1);
T = cumsum(cumsum([zeros(1,2*N);zeros(2*N-1,1),exp(sqrt(I.^2+J.^2))],1),2);
S = T(N+1:2*N,N+1:2*N)-T(N+1:2*N,1:N)-T(1:N,N+1:2*N)+T(1:N,1:N);
Array S is N-by-N with the desired values (except of course for differing rounding errors.)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

質問済み:

2016 年 6 月 14 日

回答済み:

2016 年 6 月 15 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by