How can I correctly store output from this For loop into a new variable?
2 views (last 30 days)
Show older comments
Hi!
I have a simple for loop im trying to write, wherein within an array from 1:5:150, if a number is even it is multiplied by 4 and if odd it is cubed:
a=[1:5:150]
for a=1:5:150
if rem(a,2)==0; i(a)= 4*a
else i(a)= a.^3
end
end
The output here is set to place all the modified values into a new variable ,i, however this produces a column list with intervals of 4 zeros between each value as such:
Columns 1 through 13
1 0 0 0 0 24 0 0 0 0 1331
How can I produce a single row vector output instead so that the new variable represents the output in a much neater way?
0 Comments
Accepted Answer
Image Analyst
on 19 Nov 2018
Lots of problems with that code. Just try it this way:
a=[1:5:150]
for k = 1 : length(a)
if rem(a(k),2) == 0
output(k) = 4 * a(k);
else
output(k) = a(k) .^ 3;
end
end
output
0 Comments
More Answers (1)
madhan ravi
on 19 Nov 2018
a=[1:5:150]
ctr=1;
for a=1:5:150
if rem(a,2)==0
i(ctr)= 4*a
else
i(ctr)= a.^3
end
ctr=ctr+1;
end
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!