How do you get a variable to recognized in function
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaire
Stephen23
le 5 Oct 2024
Modifié(e) : Stephen23
le 5 Oct 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.
Réponses (2)
dpb
le 4 Oct 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 commentaires
Walter Roberson
le 6 Oct 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 commentaires
Voir également
Catégories
En savoir plus sur Matrices and Arrays dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!