How to separate values of string input into other variables???

조회 수: 4 (최근 30일)
osama saeed
osama saeed 2019년 11월 30일
댓글: osama saeed 2019년 12월 1일
i want to take a string input for some calculation like 5+3 or 500-127 using single line input command and i also want to store this in a single array separated by binary of these values and than into some other variables ...like if 500*45 than a=binary of 500 b=binary of * and c=binary of 45
CODE:
clc;
clear all;
close all;
f=input('calculation:','s');
disp(f);
x=dec2bin(f);
a=(x(1,:));
b=(x(2,:));
c=(x(3,:));
But im getting binary of first three character and characters are

채택된 답변

Rik
Rik 2019년 11월 30일
I'm puzzled why you would want this. The cause of your issue is that you aren't clear about your data types. The char array in f is a list of ascii values, so 53 is stored as the ascii for 5 followed by the ascii for 3, which is the reason why you also have 5 values in x in your screenshot.
In the code below I guessed you still want the ascii converted to binary for the operator, but the two integer inputs are first converted to a numeric value to get your expected answer.
Also, the clc makes sense (since you're using the command window for user input), but the clear all;close all is totally useless and only slows down your code. Never use clear all, use clearvars instead during debugging and use functions outside of debugging. Only use close all during debugging or if you're going to open many figures, the user of your code may have figures open they want to keep.
%f=input('calculation:','s');
f='53+69';
%assume the input is only [integer][operator][integer]
op_loc=find(~isstrprop(f,'digit'));
a=f(1:(op_loc-1));
b=f(op_loc);
c=f((op_loc+1):end);
%now convert the char to a numeric value and convert that to binary
a=dec2bin(str2double(a));
c=dec2bin(str2double(c));
%convert the operator to the binary of the ascii value
b=dec2bin(b);

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by