How would I write this code using for and while loops/

4 件のコメント

James Tursa
James Tursa 2021 年 2 月 11 日
What have you done so far? What specific problems are you having with your code?
Olivia Gilliam
Olivia Gilliam 2021 年 2 月 11 日
How do I flip every entry for V?
David Hill
David Hill 2021 年 2 月 11 日
You could use if statement
for i=1:length(V)
if V(i)
V(i)=0;
else
V(i)=1;
end
end
Olivia Gilliam
Olivia Gilliam 2021 年 2 月 11 日
Yeah I finally figured out 2a of the problem. Im working on 2b, so I'm trying to flip every second instance of 0. If I do it right, array V (V = [1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1]), should become V = [1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1]. I underlined the zeroes that should flip to ones.
This is the code I used:
But, instead of getting V = [1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1]
I get:
Any help?

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

回答 (1 件)

Sourabh Kondapaka
Sourabh Kondapaka 2021 年 2 月 17 日
編集済み: Sourabh Kondapaka 2021 年 2 月 18 日

0 投票

I would recommend you to check out the free Matlab OnRamp Course
For 2b:
V = [1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1];
count = 0;
for i = 1 : length(V)
% Below 'if' condition is same as : if V(i) == 0
if ~V(i)
count = count + 1;
% As you want to modify every second instance, i'm just checking the modulus value of count
% with 2.
if mod(count,2) == 0
V(i) = 1;
end
end
end

カテゴリ

ヘルプ センター および File ExchangeMATLAB についてさらに検索

質問済み:

2021 年 2 月 11 日

編集済み:

2021 年 2 月 18 日

Community Treasure Hunt

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

Start Hunting!

Translated by