Blake
Blake

Reputation: 250

How to read in user input as binary data in MATLAB?

I am working on a program for class and we need to read in a 4-bit input (e.x. 1101) from a user and treat is as a 4-bit digital data. We then need to plot this input data and use it later to calculate the Cyclic Code base on a generator polynomial we are given.

However, after looking into MATLAB input, I'm not sure how to read in the users input as a "binary input", what would be the best way to accomplish this?

Thank you!

Here is the exact part of the instructions I am having trouble with:

Ask the user for a 4-bit input digital data and plot the user given digital data

We then use that input to do the following, which I think I should be able to do once I figure out how to get the user input!

Using the polynomial P(X) = 1 + X + X3, generate the valid codeword and transmit the codeword

Upvotes: 0

Views: 1623

Answers (1)

il_raffa
il_raffa

Reputation: 5175

You can use the input function to ask the user to insert the digit.

b4_in = input('Insert 4-bit input: ' ,'s');

The "0" "1" sequence is stored in the output variable b4_in as a string.

In MatLab binary numbers are actually string of char; you can use, for example, bin2dec to convert binary number string to decimal number).

Then you can make some check on the input validy:

  • length must be equal to 4
  • the string must contain only "0" and "1" (you can use regexp.

The whole code could be:

% Prompt for User input
b4_in = input('Insert 4-bit input: ' ,'s');
% Get the number of input digit
n_c=length(b4_in);
% Check the number of input digit
if(n_c < 4)
   disp([num2str(n_c) ': Not enough input digit. 4 digits are required'])
elseif(n_c > 4)
   disp([num2str(n_c) ': Too many input digit. 4 digits are required'])
else
   % Check if all the input digit are valid
   inv_c=regexp(b4_in,'[a-z_A-Z2-9]');
   if(~isempty(inv_c))
      disp(['Invalid char: ' b4_in(inv_c) ' idx= ' num2str(inv_c)])
   else
      % Valid input: 4 digit, only "0" or "1"
      disp([b4_in ' Valid input'])
   end
end

Hope this helps.

Qapla'

Upvotes: 1

Related Questions