How do I force MATLAB treat my variable 'range' as a variable instead of a function ?

조회 수: 9 (최근 30일)
I am doing a project for my sponsor. In the data he gives me, there is a matrix called 'range'. When I use this variable 'range' in my own function, MATLAB always treats it as its build-in function and gives me error. Since I cannot ask my sponsor to change the name of the variable, is there a way to force MATLAB treat 'range' as a variable ?
  댓글 수: 2
Firepanda415
Firepanda415 2017년 5월 2일
I call load() first, that's where problem comes from
Stephen23
Stephen23 2017년 5월 3일
  1. Never simply load into the workspace and make variables magically appear in the workspace. Always load into an output argument (which is a structure): S = load(...);
  2. Do not use the variable name range. Always use which to check if a name is already in use.
Note that if you had load-ed into a structure then this issue would never have occurred!

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

채택된 답변

Steven Lord
Steven Lord 2017년 5월 2일
I suspect you're loading the variable into the workspace via load or eval, right? That's known as "poofing" a variable into the workspace. To avoid this:
  1. Whenever I call load inside a function, I almost always call it with an output argument. This will make the output argument become a struct array with one field per variable in the MAT-file, which I can index using normal dot notation.
  2. If you cannot call load with an output, make sure in your code (prior to calling load) that you assign a value to the variable. That will tell the MATLAB parser that the identifier must be a variable, not a function, in your code and it will treat it as such.
  댓글 수: 1
Firepanda415
Firepanda415 2017년 5월 2일
You are right. I call load() in my function. Sorry I did not mention it in the description. Let me try your method.

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

추가 답변 (1개)

Alessandro
Alessandro 2017년 5월 2일
Simply create a copy of the variable assigning a different name?
  댓글 수: 3
Alessandro
Alessandro 2017년 5월 2일
편집: Alessandro 2017년 5월 2일
I still don't understand the problem, as long as the 'range' variable is correctly indicized in the function. The following MWE works for me:
function [ range ] = test( range )
range = 2*range;
end
if I call
range = [1 2;3 4];
range = test(range)
from the workspace the result is
range =
2 4
6 8
Firepanda415
Firepanda415 2017년 5월 2일
Sorry I did not make myself clear. I load a .mat which contains 'range' in my function, so it is a different situation.

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

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by