Vectorize for loop with recursion

조회 수: 2 (최근 30일)
olf nair
olf nair 2020년 3월 27일
댓글: olf nair 2020년 3월 27일
Hi all,
I have a for loop, which I'm struggeling to vectorize.
I've made a short example of what I'm trying to accomplish here.
This is not my exact code but I hope it shows the dilemma.
Does anyone have a clue?
Thanks in advance!
P1 = zeros(10,1);
P2 = zeros(10,1);
P3 = zeros(10,1);
P4 = zeros(10+1,1);
x = 1;
for i=1:10
if P4(i) > 0
P1(i) = x;
else
P2(i) = x;
end
P3(i) = P2(i) + P1(i);
P4(i+1) = P4(i) + P3(i);
end

답변 (1개)

Birdman
Birdman 2020년 3월 27일
P1(P4>0)=x;
P2(P4<0)=x;
P3=P1+P2;
P4(2:end)=P3+P4(1:end-1);
  댓글 수: 1
olf nair
olf nair 2020년 3월 27일
I was thinking about this solution too but unfortunatly this only picks up the main problem:
The if conditions depend on the exact state of P4, which isnt known in that vectorized solution yet.

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by