How do you get a variable to recognized in function
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
Stephen23
el 5 de Oct. de 2024
Editada: Stephen23
el 5 de Oct. de 2024
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.
Respuestas (2)
dpb
el 4 de Oct. de 2024
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)
0 comentarios
Walter Roberson
el 6 de Oct. de 2024
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.)
0 comentarios
Ver también
Categorías
Más información sobre Matrices and Arrays en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!