binary sequence input output

I made a random binary sequence x
I want the output to be 5 + N when x =1 and N when x = 0
How can I make this work?

Answers (2)

Walter Roberson
Walter Roberson on 11 Apr 2020
N+5*x

2 Comments

Is there any way to code using if, else?
Of course there is.
if this_x == 1
output_location = N + 5;
else
output_location = N;
end
where this_x one particular entry chosen from x, and where output_location is the place you want to store the result for this particular x entry.
You could also look at:
all_output_locations = all_N_values;
Then examining one x value at a time,
if this_x == 1
output_location = output_location + 5;
end
where this_x is one particular entry chosen from x, and where output_location refers to the corresponding location inside all_output_locations.
Yes, you are correct, I am deliberately not giving you the complete code, as it is obvious that you are working on homework involving arrays, so you should be reading about array indexing.

Sign in to comment.

Is this homework? If not, here is one way (of many):
x = randi([0, 1], 1, 20) % Create binary sequence of 0's and 1's
N = 3; % Whatever it is....
% Make everything N to start with.
output = N * ones(1, length(x))
% Now need to add 5 to ONLY those indexes in x that have a value of 1.
output(logical(x)) = output(logical(x)) + 5
You get:
x =
0 1 1 0 1 0 0 1 1 1 0 1 0 0 0 0 1 0 1 0
output =
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
output =
3 8 8 3 8 3 3 8 8 8 3 8 3 3 3 3 8 3 8 3

Categories

Find more on Programming in Help Center and File Exchange

Asked:

on 11 Apr 2020

Answered:

on 11 Apr 2020

Community Treasure Hunt

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

Start Hunting!