Vectorization of For-If combination

조회 수: 1 (최근 30일)
MAB2020
MAB2020 2020년 7월 25일
댓글: MAB2020 2020년 7월 27일
Requesting guidance on the proper vectorization methods for combinations of if statements within for loops. An example of the format referenced is included below. Code is utilizing a painful combination of if statements nested within for loops and appropriate vectorization is the only way in which this will run efficiency
X = zeros(1000,1)
C = 1:10
for A = 1:10
for B = 1:10
if C = 1
X(A*B*C) = 1;
elseif C = 2
X(A*B*C) = 2;
else
X(A*B*C) = 3;
end
end
end
  댓글 수: 2
David Hill
David Hill 2020년 7월 25일
Your code does not make sense. C is an array that does not change, your code will only execute the else statement.
X = zeros(1000,1)
C = 1:10
for A = 1:10
for B = 1:10
if C == 1%need == for comparison, this is always false
X(A*B*C) = 1;
elseif C == 2%comparison C= [1 2 3 4 5 6 7 8 9 10], this will be false
X(A*B*C) = 2;
else
X(A*B*C) = 3;%this will execute but X(1:10)=3 for for loop
end
end
end
MAB2020
MAB2020 2020년 7월 25일
% Correction, use the following code. Trying to generalize a much more complex segment.
% The overall objective is to gain a proper understanding of vectorization algorithms for
% matrix operations consisting of if statements nested within for loops
for A = 1:10
for B = 1:10
for C = 1:10
if C == 1
X(A*B*C) = 1;
elseif C == 2
X(A*B*C) = 2;
else
X(A*B*C) = 3;
end
end
end
end

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

채택된 답변

David Hill
David Hill 2020년 7월 25일
Can't think of any better way to do your problem. Only 1 loop now.
x=zeros(1000,1);
for i=1:10
x(i:i:10*i)=1;
x(2*i:2*i:20*i)=2;
x(3*i:3*i:30*i)=3;
x(4*i:4*i:40*i)=3;
x(5*i:5*i:50*i)=3;
x(6*i:6*i:60*i)=3;
x(7*i:7*i:70*i)=3;
x(8*i:8*i:80*i)=3;
x(9*i:9*i:90*i)=3;
x(10*i:10*i:100*i)=3;
end
  댓글 수: 1
MAB2020
MAB2020 2020년 7월 27일
Excellent, thank you very much for your input! I will implement this into my code and evaluate for relative performance improvement

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by