Why do I get undefined variable in an if statement?

조회 수: 3 (최근 30일)
gsourop
gsourop 2017년 10월 30일
편집: Stephen23 2017년 10월 30일
Hi everyone, I get an error for undefined function or variable in the if statement, when I have already assigned the equalities.
l_min = nan(372,1);
A = randn(372,2);
B= randn(372,3);
for t=1:372
min_ct = min( A(t,:));
if min_ct == A(t,1);
l = B(t,1);
if min_ct == A(t,2);
l = B(t,2);
elseif min_ct == A(t,3);
l = B(t,3);
end
end
l_min(t) = l;
end
Could anyone help with this one?
  댓글 수: 2
Adam
Adam 2017년 10월 30일
What is the actual error message and which line does it point to? Your indenting of the code is a bit confusing, but 'l' is not defined on all paths so far as I can see - i.e. if min_ct ~= A(t,1) then it is undefined because the other if statements sit inside the first one.
gsourop
gsourop 2017년 10월 30일
The error points the line before the last 'end'
Undefined function or variable 'l'.
Error in GenerateVariables (line 394)
l_min(t,1) = l;
What I would like to do is, compare the minimum value of a vector and make the following, if this minimum value is the first element then go to another vector and pick the first element, if it not then do the same process with the second element and so on.

댓글을 달려면 로그인하십시오.

채택된 답변

KL
KL 2017년 10월 30일
편집: KL 2017년 10월 30일
You create l inside if statements, so if none of the condition is fulfilled, then l goes undefined and when you try to access it outside that block, it throws an error.
But anyway, I noticed some other things, A only has 2 columns but you say,
min_ct == A(t,3); % I suppose A also has 3 columns
and to find minimum along columns, you could simply use (no need for loop),
[min_ct, ind_min_ct] = min(A,[],2);
now ind_min_ct has all the indices you can simply say use it to find l and l_min
  댓글 수: 3
Robert
Robert 2017년 10월 30일
I think KL got it right. ind_min_ct is now the column index of the minimum value in each row. It is simple to use this to extract the corresponding values of B.
For your data
A = randn(372, 3);
B = randn(372, 3);
You could use
[~, idx] = min(A, [], 2);
l_min = nan(372, 1);
for t = 1:372
l_min(t) = B(t, idx(t));
end
or better still
[~, idx] = min(A, [], 2);
l_min = B(sub2ind(size(B), (1:372)', idx));
That last snippet runs around 10x faster than your original code (which I interpreted as the following)
l_min = nan(372, 1);
for t = 1:372
min_ct = min( A(t, :));
if min_ct == A(t, 1)
l = B(t, 1);
elseif min_ct == A(t, 2)
l = B(t,2);
elseif min_ct == A(t, 3)
l = B(t, 3);
end
l_min(t) = l;
end
Stephen23
Stephen23 2017년 10월 30일
편집: Stephen23 2017년 10월 30일
@gsourop: your code is an extremely inefficient way to do that. Just use the second output from min (which is an index), and use that index to get the value from B.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by