How do you get a variable to recognized in function

조회 수: 4 (최근 30일)
Vinay
Vinay 2024년 10월 4일
답변: Walter Roberson 2024년 10월 6일
Everytime I run this function it say D is not recognized
GetUserInput();
filename = ['ENGR131_Lab4_CatMap_', D];
load(filename, '-mat');
PlotMap(C,D)
% B
function [C,D]=GetUserInput()
W = ['A', 'B'];
X = ['b', 'r', 'm', 'c', 'y', 'g'];
C = '';
D = '';
for i=1:2
switch i
case 1
%unable to get it too work without error W=options
prompt = 'Enter head marker body color (b, r, m, c, y, g): '
case 2
%unable to get it too work without error X=options
prompt1 = 'File (A,B): '
for I=1:2
if I == 1
while true
C = input(prompt, 's');
if any(C == X)
break;
end
end
else I == 2
while true
D = input(prompt1, 's');
if any(D == W)
break;
end
end
end
end
end
end
end
  댓글 수: 1
Stephen23
Stephen23 2024년 10월 5일
편집: Stephen23 2024년 10월 5일
Because square brackets are a concatenation operator, your code:
W = ['A', 'B'];
X = ['b', 'r', 'm', 'c', 'y', 'g'];
is equivalent to writing this:
W = 'AB';
X = 'brmcyg';
Note that using EQ on character vectors performs an element-wise comparison, which therefore throws an error if the two character vectors have incompatible sizes. If you want to write robust code use cell arrays and STRCMP or ISMEMBER or similar instead.

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

답변 (2개)

dpb
dpb 2024년 10월 4일
Because you didn't have a place to return the values from the function when you called it...so they were thrown away.
[C,D]=GetUserInput();
filename = ['ENGR131_Lab4_CatMap_', D];
load(filename, '-mat');
PlotMap(C,D)

Walter Roberson
Walter Roberson 2024년 10월 6일
function [C,D]=GetUserInput()
That code does not mean that variables C and D are to be set in the calling context. MATLAB outputs are strictly positional. Your code is equivalent to
function varargout=GetUserInput()
W = ['A', 'B'];
X = ['b', 'r', 'm', 'c', 'y', 'g'];
varargout{1} = '';
varargout{2} = '';
for i=1:2
switch i
case 1
%unable to get it too work without error W=options
prompt = 'Enter head marker body color (b, r, m, c, y, g): '
case 2
%unable to get it too work without error X=options
prompt1 = 'File (A,B): '
for I=1:2
if I == 1
while true
varargout{1} = input(prompt, 's');
if any(varargout{1} == X)
break;
end
end
else I == 2
while true
varargout{2} = input(prompt1, 's');
if any(varargout{2} == W)
break;
end
end
end
end
end
end
end
The names given to the output variables are strictly for local convenience -- they are strictly aliases for varargout (except the named variables are individually tracked as to whether they are defined or not, whereas varargout elements could in theory be skipped and get default output values.)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by