Process input string?

Hello. I want to write code:
input string signal( +,-,0), if signal(i) = '+' then bits(i)=1; if signal(i)= '-' then bits(i) = 0 .
the signal is entered from keyboard (GUI). I can't use command:
signal(i) = '+'
What is the similar-mean command? example: input signal : + - + + - + output bits: 1 0 1 1 0 1 . sorry for my bad english thank you.

Risposte (2)

Geoff Hayes
Geoff Hayes il 3 Nov 2015

0 voti

Nam - if your input string consists of +, =, and space characters, then use strrep to replace the '+' with '1' and the '-' with '0' to convert your string of - and + characters into binary 0 and 1 characters.

3 Commenti

Nam Pham
Nam Pham il 3 Nov 2015
Modificato: Geoff Hayes il 3 Nov 2015
Can you help me more specificly?
function pushbutton1_Callback(hObject, eventdata, handles)
temp = get(handles.signal,'string');
temp=str2str(temp);
bitstream=zeros(1,length(temp));
for i=0:length(temp)-1
if temp(i)=='+'
bitstream(i)=1;
elseif temp(i)=='-'
bistream(i)=0;
end
end
Using strrep you could do something like
signal = '+ + - - + + - - + -';
bitstream = str2double(strrep(strrep(strsplit(signal),'+','1'),'-','0'));
where
bitstream =
1 1 0 0 1 1 0 0 1 0
You would then need to use any(isnan(bitstream)) to check to see if there are any invalid characters in the bitstream.
The above works fine, but I think that Guillaume's answer is the more robust (preferred) one.
Nam - as an aside, in your code your for loop is set as
for i=0:length(temp)-1
Unlike some other programming languages, indexing into MATLAB arrays is one-based meaning you would do
for k=1:length(temp)
instead. Note also the use of k rather than i or j which MATLAB uses to represent the imaginary number (and so should be avoided when naming variables for indexing or other purposes).

Accedi per commentare.

Guillaume
Guillaume il 3 Nov 2015
I would do it like this:
signal = '+ - + + - +';
[~, symbol] = ismember(strsplit(signal), {'-', '+'}); %convert '-' into 1, '+' into 2, anything else into 0
if any(symbol == 0)
error('signal has some symbols other than + and - separated by spaces')
end
bitstream = symbol - 1;

Categorie

Tag

Richiesto:

il 3 Nov 2015

Commentato:

il 3 Nov 2015

Community Treasure Hunt

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

Start Hunting!

Translated by