如何在matlab中将字符串的值赋给另一个字符串

时间:2015-02-27 20:21:36

标签: string matlab math if-statement

我有一个简单的问题。我想计算训练心率。我有一些价值观。 RHR意味着静息心率。 INTEN意味着fitnes水平,我为低,中,高健身水平给出值0.55,0.65,0.8我写了代码

 Gender=input('Please input your gender: ');
 Age=input('Please input your age: ');
 RHR=input('Please enter your resting heart rate: ');
 INTEN=input('Please enter your fitness level(low,medium or high): ');
 male=Male;
 female=Female;
 low=0.55;
 medium=0.65;
 high=0.8;
 if INTEN==0.55
 INTENT=0.55;
 elseif INTENT==medium
INTENT=0.65;
else 
INTENT=0.8;
end
 if Gender==Male
 THR=((220-Age)-RHR)*INTEN+RHR;
 elseif Gender==Female
 THR=((206-0.88*Age)-RHR)*INTEN+RHR;
 end
  disp('The recommended training heart rate is ',num2str(THR))

但它给出了错误原因?

2 个答案:

答案 0 :(得分:3)

您的代码中存在一些错误。值得注意的是,您使用保留的操作来将数字与字符串进行比较,这是不可能的。此外,变量Gender应该是一个字符串,但是被操作为一个数字,这是令人困惑的。请务必查看用于将字符串进行比较的函数strcmp。然后,您可以使用if/elseif块。

我建议使用prompt来查询用户的信息。这样一切都在同一时间显示,在我看来更容易使用。

以下是带注释的代码。如果有什么不清楚请告诉我。

clc
clear

%// Set up dialog promt.
prompt = {'Enter your gender (male/female)','Enter your age:','Enter your resting heart rate: ','Enter your fitness level(low,medium or high): '};
dlg_title = 'Input';
num_lines = 1;

%// Default answers
def = {'male','30','120','medium'};

%// The answers are stored in the cell array called "answer". Its a 4x1
%// cell array containing ONLY STRINGS.
answer = inputdlg(prompt,dlg_title,num_lines,def);

%// Transform the strings into numbers that you can use.
Gender = answer{1};
Age = str2double(answer{2});
RHR = str2double(answer{3});
INTEN = answer{4};

%// A switch/case statement to convert INTEN into the number used for
%// the calculation
switch INTEN
    case 'low'
        INTEN=0.55;
    case 'medium'
         INTEN=0.65;
    case 'high'
        INTEN=0.8;
end

%// Use strcmp to compare strings. 
if strcmp(Gender,'Male') || strcmp(Gender,'male')

    THR=(220-Age-RHR)*INTEN+RHR;

elseif strcmp(Gender,'Female') || strcmp(Gender,'female')

    THR=((06-0.88*Age)-RHR)*INTEN+RHR;

end

%// Create a string to display
DispMessage = sprintf('The recommended training heart rate is %0.2f\n',THR);

%// Create a message box to display the above string.
msgbox(DispMessage)

以下是提示窗口的样子:

enter image description here

并显示消息:

enter image description here

希望有所帮助!

答案 1 :(得分:0)

Matlab无法弄清楚你给出的是什么。正确的版本是:

 Gender=input('Please input your gender: ','s');

此外,您的代码中还有更多错误,我建议您自行修复。我的不太先进的版本然后abowe:

Gender=input('Please input your gender: ','s');
Age=input('Please input your age: ');
RHR=input('Please enter your resting heart rate: ');
INTEN=input('Please enter your fitness level(low,medium or high): ','s');
if strcmp(INTEN,'low')
INTENT=0.55;
elseif strcmp(INTEN,'medium')
INTEN=0.65;
else 
INTEN=0.8;
end

if strcmp(Gender,'male')|| strcmp(Gender,'Male')
THR=((220-Age)-RHR)*INTEN+RHR;
if strcmp(Gender,'female')|| strcmp(Gender,'Female')
THR=((206-0.88*Age)-RHR)*INTEN+RHR;
end

printres=['The recommended training heart rate is ',num2str(THR)];
disp(printres)