Logical Indexing instead of for (if) loop
Mostra commenti meno recenti
I'd like to write the following piece of code usiging Logical indexing instead of for loop with if condition.
As you can see, I commented the original code, wheareas the alternative code is not. CAR_GEN is the main input matrix (with 10000 rows), Y_car_gen is a matrix (10000x10000), En is a column vector (10000x1). So:
- If I run the first code (with for loop) no problem.
- But if I run the second code Matlab says to me that I have a problem:
Error using ^ in N(a-1,1) = -(abs(En(Ngen)))^2*conj(Y_car_gen(Ngen,Ngen));
Incorrect dimensions for raising a matrix to a power. Check that the matrix is square and the power is a scalar.
To perform elementwise matrix powers, use '.^'.
My question is: why this dimension problem doesn't exist in the first code? Have I to modify something in the second code?
%Initializing N & Ncorr
N = zeros(10000 - 1,1);
Ncorr = zeros(10000 - 1,1);
% for Riga = 2:10000
%
% if CAR_GEN(Riga,1) == abs('G')
% Ngen = CAR_GEN(Riga,2);
% N(Riga-1,1) = -(abs(En(Ngen)))^2*conj(Y_car_gen(Ngen,Ngen));
% Ncorr(Riga-1,1) = En(Ngen).*conj(Ix(Ngen-1));
% else
% Ncar = CAR_GEN(Riga,2);
% N(Riga-1,1) = (abs(En(Ncar)))^2*conj(Y_car_gen(Ncar,Ncar));
% Ncorr(Riga-1,1) = -En(Ncar).*conj(Il(Ncar-N_nodi_gen));
% end
%
% end
--------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------
CAR_GEN2 = CAR_GEN(2:end,:);
a = (CAR_GEN2(:,1) == abs('G'));
Ngen = CAR_GEN2(a,2);
N(a-1,1) = -(abs(En(Ngen)))^2*conj(Y_car_gen(Ngen,Ngen)); %PROBLEM!
Ncorr(a-1,1) = En(Ngen).*conj(Ix(Ngen-1));
b = (CAR_GEN2(:,1) == abs('C'));
Ncar = CAR_GEN2(b,2);
N(b-1,1) = (abs(En(Ncar)))^2*conj(Y_car_gen(Ncar,Ncar)); %PROBLEM!
Ncorr(b-1,1) = -En(Ncar).*conj(Il(Ncar - N_nodi_gen));
Risposta accettata
Più risposte (0)
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!