Problem introducing user input into an array

Hey guys, im new to matlab and i have a problem. I have to create a simulator of an RZ signal coding.
I have made the part where the user adds the 1´s and 0´s but when i want to creat a array to assing values to the 1´s and 0´s i just dont ge it why its not working
heres the code
% ask the user
bny = input('Insira o codigo a codificar: ' ,'s');
% Verifyif only 0´s and 1´s
inv_c=regexp(bny,'[a-z_A-Z2-9]');
if(~isempty(inv_c))
disp(['O seu código não é válido: ' bny(inv_c) ' Valores não validos= ' num2str(inv_c)])
else
% its valid
disp(['your code is : ', bny ])
end
for i = 1 : length(bny)
if bny(i) == 1
n(i)=3;
else
n(i)=-3;
end
end

2 件のコメント

Walter Roberson
Walter Roberson 2019 年 1 月 9 日
Note: I recommend you change
inv_c=regexp(bny,'[a-z_A-Z2-9]');
to
inv_c = regexp(bny, '[^01]');
for example ';' is not one of the characters you listed and so your checking would permit through ';'.
António Pereira
António Pereira 2019 年 1 月 9 日
thanks for the note!

サインインしてコメントする。

 採用された回答

Stephen23
Stephen23 2019 年 1 月 9 日
編集済み: Stephen23 2019 年 1 月 9 日

0 投票

Simpler:
bny = input('Insira o codigo a codificar: ' ,'s');
idx = ismember(bny,'01');
assert(all(idx),'Input must contain only 0s and 1s, but it contains %s',bny(~idx))
fprintf('Your code is: %s\n',bny)
V = [-3,3];
n = V(bny-'/')

3 件のコメント

António Pereira
António Pereira 2019 年 1 月 9 日
That code is giving me a error, "Index exceeds the number of array elements (2)."
Stephen23
Stephen23 2019 年 1 月 9 日
@António Pereira: I fixed the last line of code and tested it:
Insira o codigo a codificar: 1101101
Your code is: 1101101
n =
3 3 -3 3 3 -3 3
António Pereira
António Pereira 2019 年 1 月 9 日
Thanks a lot!!! Not only it looks nicer as it works nicely

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2019 年 1 月 9 日

0 投票

You are reading in characters. You have
if bny(i) == 1
but this is comparing the character in bny(i) to the number 1. The character is '0' or '1' which are not numeric 0 or 1 -- they are numeric 48 and 49.
You can vectorize your code.
n = 3 * ((bny - '0') * 2 - 1)
or somewhat more obscurely,
n = bny * 6 - 291;

3 件のコメント

António Pereira
António Pereira 2019 年 1 月 9 日
Can you explain why do that way??
Walter Roberson
Walter Roberson 2019 年 1 月 9 日
bny is '0' or '1'. When you subtract '0' then you get numeric 0 or 1. Multiply by 2 to get numeric 0 or 2. Subtract one from that to get numeric -1 or +1 . Multiply by 3 to get -3 or +3.
The second form with the 291 is an optimization of the first one. '0' is equal to 48 and 291 is 48*6 - 3 -- i.e., (6 * bny - 6 * '0' - 3) which is the result of expanding 3 * ((bny - '0') * 2 - 1)
António Pereira
António Pereira 2019 年 1 月 10 日
I got it, someone showed me a way to make it work, but thanks anyway for your time

サインインしてコメントする。

カテゴリ

Community Treasure Hunt

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

Start Hunting!

Translated by