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?

回答(2 个)

Walter Roberson
Walter Roberson 2020-4-11

0 个投票

N+5*x

2 个评论

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.

请先登录,再进行评论。

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

类别

帮助中心File Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by