Azzera filtri
Azzera filtri

Info

Questa domanda è chiusa. Riaprila per modificarla o per rispondere.

Indexing in for loop in order to remove non-zero and nan entries from vectors

1 visualizzazione (ultimi 30 giorni)
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);

Risposte (1)

Todd Leonhardt
Todd Leonhardt il 18 Mag 2016
Modificato: Todd Leonhardt il 18 Mag 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 Commento
hello_world
hello_world il 18 Mag 2016
Modificato: hello_world il 18 Mag 2016
I know, and I am trying to fix it, but still no success. In
P1 = P(M{i}~=0);
M{i} is AB, a cell, while P is double. If I change AB to cell to double, it does not work. It should actually take values stored in AB, and not just characters AB.

Questa domanda è chiusa.

Community Treasure Hunt

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

Start Hunting!

Translated by