How can I fix my while loop?

Hi!
I am trying to create a program that reads a cell array and computes the answer ex:
t = {'mult','add','2','3','stop','add','4','5','stop','stop'} (So the equation is (2+3)*(4+5))
ans= 45.0000
here is my current code:
function [pos prod] = doMult ( expr, pos )
prod=1;
lm=length(expr)
expo=1;
sub=1;
quot=1;
sum=1;
while ~strcmp(expr{pos}, 'stop')
pos=pos+1
if strcmp(expr{pos}, 'pow')
[pos expo]=doPow(expr, pos)
elseif strcmp(expr{pos},'mult')
[pos prod]=doMult(expr, pos)
elseif strcmp(expr{pos}, 'div')
[pos quot]=doDiv(expr, pos)
elseif strcmp(expr{pos},'add')
[pos sum]=doAdd(expr, pos)
elseif strcmp(expr{pos},'sub')
[pos diff]=doSub(expr, pos)
else
ExprNUM=str2double(expr) %double type
prod=prod* ExprNUM(1,pos)*sum*diff*quot*expo
pos=pos
end
end
end
and the other finctions for doAdd and such would contain some variation of this . the output gives me an answer of 5, which is not correct. After going through what it calculates here:
lm =
10
pos =
2
lm =
10
pos =
3
ExprNUM =
NaN NaN 2 3 NaN NaN 4 5 NaN NaN
sum =
2
pos =
3
pos =
4
ExprNUM =
NaN NaN 2 3 NaN NaN 4 5 NaN NaN
sum =
5
pos =
4
pos =
5
ExprNUM =
NaN NaN 2 3 NaN NaN 4 5 NaN NaN
sum =
NaN
pos =
5
pos =
5
sum =
NaN
answer =
5
ans =
5
and it looks like it is not recognizing the stop and the function following it. How can I fix this?
Thanks!

1 个评论

Ashley - maybe you need to start with a simpler example and/or post more of your code. Is doMult the calling function or do you have some other function that you call first?
Note that if I try something simple like
g = {'mult' '2' '3' 'stop' }
doMult(g,1)
then I get an error
Undefined function or variable "diff".
Error in doMult (line 25)
prod=prod* ExprNUM(1,pos)*sum*diff*quot*expo
which makes sense because neither sum nor diff have been defined.
NOTE that sum and diff are built-in MATLAB functions so you should not be creating variables with the same names as these functions.

请先登录,再进行评论。

回答(0 个)

类别

帮助中心File Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by