Getting rid of for loop in one-liner code
Show older comments
Lets assume we have an optimization problem like this:
x = zeros(1,10);
x(1,1) = 2;
for k = 1: 9
x(k+1) = 10 x(k);
end
Is it possible to write the equation without the for loop?
Accepted Answer
More Answers (1)
John BG
on 13 Feb 2017
this
x = zeros(1,10);
x(1) = 2;
for k = 1: 9
x(k+1) = 10 *x(k);
end
x
=
Columns 1 through 3
2.00 20.00 200.00
Columns 4 through 6
2000.00 20000.00 200000.00
Columns 7 through 9
2000000.00 20000000.00 200000000.00
Column 10
2000000000.00
is the same as
n=[1:1:10];x=.2*10.^n
x =
Columns 1 through 3
2.00 20.00 200.00
Columns 4 through 6
2000.00 20000.00 200000.00
Columns 7 through 9
2000000.00 20000000.00 200000000.00
Column 10
2000000000.00
if you find this answer useful would you please be so kind to mark my answer as Accepted Answer?
To any other reader, please if you find this answer of any help solving your question,
please click on the thumbs-up vote link,
thanks in advance
John BG
3 Comments
Sakil Chowdhury
on 13 Feb 2017
Walter Roberson
on 13 Feb 2017
More compactly,
x = 2 * 10.^(0:9);
Jan
on 14 Feb 2017
@Sakil: The operation A.^(0:9) is not valid, therefore the readers have to guess, what you want as result. Which dimension does x have after this calculation?
Categories
Find more on MATLAB 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!