Unbalanced or unexpected parenthesis or bracket.
Mostra commenti meno recenti
I am trying to come out with a program that can evaluate a postfix string arithmetically. But I keep getting errors when I'm trying to define an input for my codings. Would appreciate it greatly if any kind hearted soul can help to point out my mistakes and provide solutions. The following is my codings:
function Expression=fn(x)
x=[1 4 5 ^ - 8 + 5 4 * -]
n=size(x,2);
y=0;
N=n;
while x(n)~='+' || x(n)~='-' || x(n)~='*' || x(n)~= '/'||x(n)~='^'
n=n-1;
end
if x(n)=='+'
y=x(n-1)+x(n-2);
elseif x(n)=='-'
y=x(n-1)-x(n-2);
elseif x(n)=='*'
y=x(n-1)*x(n-2);
elseif x(n)=='/'
y=x(n-1)/x(n-2);
elseif x(n)=='^'
y=x(n-1)^x(n-2);
end
for i=n+1:1:N
if x(i)=='+'
y=y+x((2*n)-2-i);
elseif x(i)=='-'
y=y-x((2*n)-2-i);
elseif x(i)=='*'
y=y*x((2*n)-2-i);
elseif x(i)=='/'
y=y/x((2*n)-2-i);
end
end
Expression=y;
end
1 Commento
Alexandra Harkai
il 8 Feb 2017
The error "Unbalanced or unexpected parenthesis or bracket." Does point out which line the problem occurs in.
There are lots of problems with the code though in general, to name a few:
- The function seems to behave weirdly, input argument x is overwritten in the first step which is not necessarily what you want.
- Also your input x needs to be a character array, like this one: x='3+4'
- The while loop only changes n and then leaves it like that. This way, it is not looping through the input string.
Risposte (2)
x=[1 4 5 ^ - 8 + 5 4 * -]
is not valid code. If you want an array of characters you have to use e.g. '1', '4',...'*'
As an aside, why are you defining x the first line of a function in which you passed it in as an argument? I haven't even looked at the rest of the code as there isn't much point. Your first error is the above statement.
This is not valid Matlab syntax:
x = [1 4 5 ^ - 8 + 5 4 * -]
I guess you want the string:
x = '145^-8+54*-'
The following loop must fail:
n = size(x,2);
while x(n)~='+' || x(n)~='-' || x(n)~='*' || x(n)~= '/'||x(n)~='^'
n = n-1;
end
The condition that a character x(n) is not '+' or is not '-' or is not ... is always true and the loop runs until n=0, where it fails, because x(0) is invalid.
A comment in the code would help to clarify what the code should do. I guess, you want:
while all(x(n) ~= '+-*/^') && n > 1
y=x(n-1)+x(n-2) will most likely not do, what you expect, when the inputs are characters and not numbers. You can convert from character to number by:
v = x(n) - '0'
Categorie
Scopri di più su MATLAB in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!