Logical Indexing instead of for (if) loop
Show older comments
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));
Accepted Answer
More Answers (0)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!