How do you get a variable to recognized in function

5 次查看(过去 30 天)
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