way to avoid for loops
Mostra commenti meno recenti
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
Risposte (2)
Roger Stafford
il 14 Giu 2016
Modificato: Roger Stafford
il 14 Giu 2016
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 Commento
Rahul Shaw
il 15 Giu 2016
Roger Stafford
il 15 Giu 2016
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.)
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!