Info
Diese Frage ist geschlossen. Öffnen Sie sie erneut, um sie zu bearbeiten oder zu beantworten.
How can I have a function that has a string as the input.
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentar
Stephen23
am 1 Apr. 2018
Do NOT use == to check if character vectors are the same. Use strcmp or strcmpi.
Antworten (1)
David Fletcher
am 31 Mär. 2018
Bearbeitet: David Fletcher
am 31 Mär. 2018
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 Kommentare
Walter Roberson
am 1 Apr. 2018
if strcmp(color, 'black')
The input to the function would be like displayColor('black')
Diese Frage ist geschlossen.
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!