How can I have a function that has a string as the input.

I am trying to make a function that requires you to input the name of a color to get the output. My code, for example, is:
function [] = displayColor(color)
if color == 'black'
disp('black line');
plot(x.^2);
elseif color == 'blue'
disp('blue line');
plot(x.^3);
end
When I do this, I get the error:
Error using ==
Matrix dimensions must agree.
Error in displayColor (line 4)
if color == 'black'
How do I fix this so I can input a string as the function variable??

1 件のコメント

Stephen23
Stephen23 2018 年 4 月 1 日
Do NOT use == to check if character vectors are the same. Use strcmp or strcmpi.

回答 (1 件)

David Fletcher
David Fletcher 2018 年 3 月 31 日
編集済み: David Fletcher 2018 年 3 月 31 日

0 投票

You need to use strcmp(string1,string2) to compare as the size of the color variable might be a different length to whatever fixed length string you are trying to equate it with (which is why you are getting the error).

3 件のコメント

Walter Roberson
Walter Roberson 2018 年 3 月 31 日
Note that you would not get this error if you really did have a string as an input. But you do not: instead you have a character vector as input. You need strcmp() or strcmpi() to compare character vectors.
spete
spete 2018 年 4 月 1 日
Hi I am still confused. So if I put in displayColor(black), I then add strcmp(black) before the code of the function?
Walter Roberson
Walter Roberson 2018 年 4 月 1 日
if strcmp(color, 'black')
The input to the function would be like displayColor('black')

この質問は閉じられています。

質問済み:

2018 年 3 月 31 日

閉鎖済み:

2021 年 8 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by