필터 지우기
필터 지우기

Replacement for for loops

조회 수: 1 (최근 30일)
Dhananjay Mishra
Dhananjay Mishra 2018년 10월 12일
댓글: Star Strider 2018년 10월 12일
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

채택된 답변

Star Strider
Star Strider 2018년 10월 12일
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
Dhananjay Mishra
Dhananjay Mishra 2018년 10월 12일
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 2018년 10월 12일
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))

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by