General questions about function and if command.

조회 수: 1 (최근 30일)
C Zeng
C Zeng 2012년 10월 23일
1. If I have a variable x, and I use a nested function f and in f.m, there is also a variable x but not equal to the first x. Will it bother the program? The x's are defined in different functions, will matlab recognize these?
2. I have an error message: --- Operands to the and && operators must be convertible to logical scalar values.
Error in V_F (line 16) if P(n)>0 && x>n-1 ---
However, P(n) is scalar and x is also scalar. What is wrong here?
Thanks.

답변 (2개)

Matt Fig
Matt Fig 2012년 10월 23일
편집: Matt Fig 2012년 10월 23일
For the first question, it makes a difference how and where you are accessing the variables. Post a simple example for anlaysis. For the second question, are you sure P is not a cell array and P(n) is not nan? Are you sure n is a scalar and not empty or nan? Are you sure x is a scalar and not empty or nan?
  댓글 수: 1
C Zeng
C Zeng 2012년 10월 23일
Hi, Matt, thanks in advance!
(1) For example, in my current program, I define x as a vector, like x=zeros(1,N). I also define a function f(a,b,c) note f has nothing with x. In f.m file, I write a code to find the f_value, including define auxiliary variable x which is a scalar. By doing so, it seems to me that it will not affect any confusion, and by convention, matlab will not make any problem, right?
(2)Let me double check it. I think they are all well defined and will not be empty or infinity.

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


Walter Roberson
Walter Roberson 2012년 10월 23일
There might perhaps be a code path in which your local "x" does not get initialized in the subfunction on and so inherits the scalar value.
  댓글 수: 3
Walter Roberson
Walter Roberson 2012년 10월 23일
Suppose you have
if a > 3
x = 15;
elseif a < 3
x = 22;
end
then it might at first look like x is always being initialized, but in fact in the case that a is exactly 3, there would be a path in which x was not set, and so in that case would inherit its value from the nesting function.
C Zeng
C Zeng 2012년 10월 26일
Thanks, Walter, so in this case x is not well defined? Will it cause any problem to nested function?

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

카테고리

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