How do I replace "for" loops by matrix multiplication? I am getting confused because of 4 "for" loops. Any suggestions?
Afficher commentaires plus anciens
Hello, the code is as follows.
value = zeros();
E2 = zeros();
dxdy = 1;
x1=1;y1=1;u1=1;v1=1;
for u = -1:1:1
for v = -1:1:1
for x = -1:1:1
for y = -1:1:1
value(x1,y1) = input_data(x1,y1)*exp( ( -1i*k*(((u-x)^2) + (v-y)^2)) / (2*0.2))*(dxdy);
y1 = y1+1;
end
x1 = x1+1;
y1 = 1;
end
S_rows = sum(value,2); %Adding components of matrix "value"
S_complete = sum(S_rows);
E2(u1,v1) = S_complete;
x1 = 1;
v1 = v1 + 1;
end
u1 = u1+1;
v1 = 1;
end
disp(E2)
4 commentaires
madhan ravi
le 11 Oct 2018
what's input_data?
Dhananjay Mishra
le 11 Oct 2018
Modifié(e) : Dhananjay Mishra
le 11 Oct 2018
Torsten
le 11 Oct 2018
"input_data" must be 27x3, not 3x3.
Dhananjay Mishra
le 12 Oct 2018
Réponses (1)
dxdy = 1;
[x,y,u,v] = ndgrid(-1:1);
value = input_data.*exp((-1i*k*(((u-x).^2) + (v-y).^2))/(2*0.2))*(dxdy);
S_rows = sum(value,2);
S_complete = sum(S_rows);
E2 = squeeze(S_complete);
disp(E2)
8 commentaires
Dhananjay Mishra
le 12 Oct 2018
Miriam
le 12 Oct 2018
What is k in your code? I assumed it was scalar and just used 1.
Dhananjay Mishra
le 12 Oct 2018
Do you get the same error with the following command?
[1 2].*[3 4;5 6]
This causes no issues with my version of MATLAB.
Dhananjay Mishra
le 12 Oct 2018
Miriam
le 12 Oct 2018
Odd there are no issues on my end. Perhaps try this instead:
value = repmat(input_data,1,1,3,3).*exp((-1i*k*(((u-x).^2) + (v-y).^2))/(2*0.2))*(dxdy);
Dhananjay Mishra
le 12 Oct 2018
Miriam
le 12 Oct 2018
I'm not sure what to tell you then. It works fine for me.
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!