Beginner question about for loops and indexing

1 回表示 (過去 30 日間)
Callum Taylor
Callum Taylor 2018 年 11 月 20 日
コメント済み: Callum Taylor 2018 年 11 月 21 日
I want to perform a function on each number in a series 'a' depending on whether it's odd or even. Then output this series of numbers 'b' as an array.
I don't know what to do next. So far my script doesn't output anything.
a = 1:5:150; % array before function applied
b = zeros(1,30); % used to store numbers from a after functions
counter = 0;
for series = [1:30]
r = rem(a,2); % r = 0 if number is even, r = 1 if number is odd
counter = counter + 1;
if r == 0
b = a(counter)*4 % if number in b is even, multiply it by 4
elseif r == 1
b = a(counter)^3 % if number in a is odd, cube it
end
end
I am an absolute beginner, really have no idea what I'm doing, please help?

採用された回答

Brian Hart
Brian Hart 2018 年 11 月 20 日
Hi Callum,
You're really close.
First, you can move the "r = ... " line outside the loop to do the operation on the whole array at once.
Then inside the loop, you need to index the other variables the same way you did with "a(counter)".
So it looks like this:
a = 1:5:150; % array before function applied
b = zeros(1,30); % used to store numbers from a after functions
counter = 0;
r = rem(a,2); % r = 0 if number is even, r = 1 if number is odd
for series = [1:30]
counter = counter + 1;
if r(counter) == 0
b(counter) = a(counter)*4; % if number in b is even, multiply it by 4
elseif r(counter) == 1
b(counter) = a(counter)^3; % if number in a is odd, cube it
end
end
  2 件のコメント
Brian Hart
Brian Hart 2018 年 11 月 21 日
To encourage you to learn more about MATLAB, here's a different solution that does the same thing with few lines of code...
a = 1:5:150; % array before function applied
b = zeros(1,length(a)); % used to store result
b(rem(a,2)==0) = a(rem(a,2)==0) * 4; % Using logical indexing and vectorization
b(rem(a,2)==1)=a(rem(a,2)==1).^3;
Callum Taylor
Callum Taylor 2018 年 11 月 21 日
Thank you so much! It works just fine now. I didn't know you had to index every variable, including 'r'.
I definitely need more practice, thanks for the help!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by