Process input string?

8 views (last 30 days)
Nam Pham
Nam Pham on 3 Nov 2015
Commented: Geoff Hayes on 3 Nov 2015
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.

Answers (2)

Geoff Hayes
Geoff Hayes on 3 Nov 2015
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 Comments
Geoff Hayes
Geoff Hayes on 3 Nov 2015
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.
Geoff Hayes
Geoff Hayes on 3 Nov 2015
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).

Sign in to comment.


Guillaume
Guillaume on 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;

Tags

Community Treasure Hunt

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

Start Hunting!