How do you get a variable to recognized in function

5 ビュー (過去 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 Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by