필터 지우기
필터 지우기

making a function that uses a string input

조회 수: 89 (최근 30일)
Sean Smith
Sean Smith 2011년 10월 20일
I am trying to make a function:
function [y]=my_function(A,B,C)
where A is a string and B and C are just numbers. If someone enters 'yes' for A then a number for B and C I want it to do one calculation. If someone enters 'no' for A then numbers for B and C I want it to do another calculation. I was trying to use if statements i.e.
if A='yes'
calculations
end
if A='no'
calculations
end
but I can't get the function to accept strings and then use them with the if statements. Is there a way to do this or am I way off? Thanks. Let me know if I wasn't clear with something.

채택된 답변

Walter Roberson
Walter Roberson 2011년 10월 20일
if A='yes'
attempts to assign 'yes' to A in the middle of the 'if' statement. This is... not good.
if A=='yes'
would attempt to compare A to 'yes'. Which will work if A happens to be a row vector with exactly three elements (the same size as 'yes'), but will fail with a dimension mismatch if A happens to be a different size, such as if A is a row vector with two elements containing 'no' . Using '==' to compare strings is thus not recommended.
For your situation, I would suggest you use strcmpi()

추가 답변 (1개)

Jun
Jun 2011년 10월 20일
You can try strcmp or strcmpi
for example, if strcmp(A,'yes')...

카테고리

Help CenterFile Exchange에서 String에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by