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

Antworten (2)

Roger Stafford
Roger Stafford am 14 Jun. 2016
Bearbeitet: Roger Stafford am 14 Jun. 2016

2 Stimmen

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 Kommentar

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

Melden Sie sich an, um zu kommentieren.

Roger Stafford
Roger Stafford am 15 Jun. 2016

0 Stimmen

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

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Produkte

Gefragt:

am 14 Jun. 2016

Beantwortet:

am 15 Jun. 2016

Community Treasure Hunt

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

Start Hunting!

Translated by