Clear Filters
Clear Filters

Replacement for for loops

1 view (last 30 days)
Dhananjay Mishra
Dhananjay Mishra on 12 Oct 2018
Commented: Star Strider on 12 Oct 2018
Hello everyone. I want to construct an array of data which will contain values like below example. Any suggestions on how to do this without using for loop will be very helpful. Thank you!
A = zeros();
x1 = 1
for u = -1:1:1
for v = -1:1:1
A(x1) = exp((-1i*(u-v).^2)/2);
x1 = x1+1;
end
end

Accepted Answer

Star Strider
Star Strider on 12 Oct 2018
Try this:
[U,V] = meshgrid(-1:1);
Am = exp((-1i*(U-V).^2)/2);
A = Am(:).';
It produces the same output as your code.
  2 Comments
Dhananjay Mishra
Dhananjay Mishra on 12 Oct 2018
Many thanks for your answer. However how to remove for loop if I have a code like this: I am new to MATLAB hence having problems implementing the code
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) = exp( ( -1i*(((u-x)^2) + (v-y)^2))
y1 = y1+1;
end
x1 = x1+1;
y1 = 1;
end
x1 = 1;
v1 = v1 + 1;
end
u1 = u1+1;
v1 = 1;
end
Star Strider
Star Strider on 12 Oct 2018
As always, my pleasure.
I cannot understand what you want to do. If your code produces the result you want, just leave it as is. I doubt it can be vectorised.
Also, there are too many parentheses in your ‘value’ assignment, so it throws an error. I eliminated one left parenthesis to make it work:
value(x1,y1) = exp(-1i*((u-x)^2 + (v-y)^2))

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!