Process input string?

조회 수: 9 (최근 30일)
Nam Pham
Nam Pham 2015년 11월 3일
댓글: Geoff Hayes 2015년 11월 3일
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.

답변 (2개)

Geoff Hayes
Geoff Hayes 2015년 11월 3일
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
Geoff Hayes
Geoff Hayes 2015년 11월 3일
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 2015년 11월 3일
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).

댓글을 달려면 로그인하십시오.


Guillaume
Guillaume 2015년 11월 3일
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;

카테고리

Help CenterFile Exchange에서 Symbolic Math Toolbox에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by