Info

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

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

조회 수: 2 (최근 30일)
hello_world
hello_world 2016년 5월 18일
마감: MATLAB Answer Bot 2021년 8월 20일
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);

답변 (1개)

Todd Leonhardt
Todd Leonhardt 2016년 5월 18일
편집: Todd Leonhardt 2016년 5월 18일
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
hello_world
hello_world 2016년 5월 18일
편집: hello_world 2016년 5월 18일
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.

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

Community Treasure Hunt

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

Start Hunting!

Translated by