Hi Guys I need help. I need to get user input of a postfix expression and then evaluate the expression. But, I am having trouble in storing the postfix expression in a variable and then to read it by one character at a time.
조회 수: 1 (최근 30일)
이전 댓글 표시
for example, the user inputs a postfix expression, a = 123*+ I don't know how to split this expression into individual characters, like b = 1 2 3 * + Pls help!
댓글 수: 1
Walter Roberson
2017년 2월 7일
Duplicates http://www.mathworks.com/matlabcentral/answers/323017-need-to-write-a-program-that-evaluates-a-postfix-expression-which-is-input-by-the-user-and-then-disp and should be merged with it.
채택된 답변
John Chilleri
2017년 2월 7일
Hello,
If I was to solve this problem and I had,
a = '123*+';
I would parse the data as follows (perhaps think of a better method than using a cell, because it's definitely not required here):
data = cell(length(a),1);
for i = 1:length(a)
if (sum(a(i) == '0123456789') == 1)
% We know a(i) is a number so
data{i} = str2num(a(i));
else
data{i} = a(i);
end
end
At this point, you have a variable named data with each element containing a character or number (if it's a number), which will be useful when you start doing operations.
Furthermore, you can do simple tests on the operation characters, such as:
if (data{i} == '+')
% perform addition
elseif (data{i} == '*')
% perform multiplication
end
If you have any questions please ask! Also, in case you aren't familiar with cells, it's essentially an array that can hold 'anything' in each element, and you can access elements with curly brackets:
data{1} = % first element of data
Hope this helps!
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 String Parsing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!