필터 지우기
필터 지우기

Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

Avoiding for loop and if

조회 수: 1 (최근 30일)
Giovanni Gardan
Giovanni Gardan 2020년 5월 19일
마감: MATLAB Answer Bot 2021년 8월 20일
I'd like to avoid the following "for loop". Is it possible?
In the following code, the matrix CAR_GEN is the input. This matrix has rows number=1000, and column number=4. In the first column of this matrix there are two possibilities: or 'G' or 'C', and if I have 'C' i have to do the operation under the if-test and finally find the vector ''Scarto''.
Is it possible to check directly if the element of the first column is 'C' and then do the operation in order to find 'Scarto', in order to save time?
-----------------------------------------------------------------------------------------------------------------------------
Scarto = zeros (N_nodi_tot - N_nodi_gen,1); %Array initialization
for Riga = 1:100000
if CAR_GEN(Riga,1) == abs('C')
Ncar = CAR_GEN(Riga,2);
Pcar = CAR_GEN(Riga,3)/Nbase;
Qcar = CAR_GEN(Riga,4)/Nbase;
Nload = Ntot(Riga,1);
Scarto(Ncar,1) = Nload - (Pcar + 1i*Qcar);
end
end
---------------------------------------
----------------------------------------------------------------------------------------
Thanks!
  댓글 수: 3
Giovanni Gardan
Giovanni Gardan 2020년 5월 19일
Thank you very much for your answer. Is this the right way to use logical indexing?
Scarto = zeros (N_nodi_tot - N_nodi_gen,1);
cond = (CAR_GEN(:,1) == abs('C'));
Ncar = CAR_GEN(cond,2);
Pcar = CAR_GEN(cond,3)/Nbase;
Qcar = CAR_GEN(cond,4)/Nbase;
Nload = Ntot(cond,1);
Scarto(Ncar,1) = Nload - (Pcar + 1i*Qcar);
Walter Roberson
Walter Roberson 2020년 5월 19일
Looks plausible.

답변 (0개)

이 질문은 마감되었습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by