Info
La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.
Indexing in for loop in order to remove non-zero and nan entries from vectors
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hello Friends,
I have the following code:
P = [1, 0, 3];
Q = [0, 4, 5];
% These AB, CD, EF are just for illustration purpose. They could be any to make AB, CD , EF equal size vectors.
AB = [P + Q]; % A vector
CD = [P - Q]; % A vector
EF = [P ./ Q]; % A vector
% Now I want to pass above compute vectors AB, CD, EF in for loop. I try as follows:
M = {'AB', 'CD', 'EF'};
for i = 1:length(M)
P1 = P(M{i}~=0); %It removes those elements of P which correspond to 0 entries in M.
t = M{i}; %Create a temporary variable.
M = t(M{i}~=0); %It removes 0 entries from M.
P = P1(~isnan(M(i))); %It removes those elements of P which correspond to NaN entries in M.
M = t(~isnan(M(i))); %It removes NaN entries from M.
if strcmp(M, 'AB')
f = f(P,M);
elseif strcmp(M, 'CD')
f = g(Q,M);
elseif strcmp(M, 'EF')
f = h(R,M);
end
end
This code is not computing P1, t, M, P values properly. For example the following line of code takes M{i} = AB for i = 1, but gives totally wrong answer.
I have tried to change {} to () and [], etc., but nothing works. I will appreciate any advice.
P1 = P(M{i}~=0);
0 comentarios
Respuestas (1)
Todd Leonhardt
el 18 de Mayo de 2016
Editada: Todd Leonhardt
el 18 de Mayo de 2016
The problem appears to be that your loop changes M into something with a single element on the first pass through, but then tries to access the 2nd element on the 2nd pass through.
On the first pass through (i=1), this following line sets M equal to 'AB'
M = t(M{i}~=0)
Then this line mutates it further to just 'A':
M = t(~isnan(M(i)));
So on the 2nd pass through your loop (i=2), this line tries to access the 2nd element in the M cell array, but there is only 1 element:
P1 = P(M{i}~=0);
1 comentario
La pregunta está cerrada.
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!