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

4 views (last 30 days)
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

Accepted Answer

Rik
Rik on 30 Nov 2019
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);

More Answers (0)

Categories

Find more on Environment and Settings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!