Hi, I would like create a vector using a for loop.

1 view (last 30 days)
P=1e3;
i=6;
for i=1:length(i)
X(i)=P/1e3
end
I expect following results
X=[1e3 1e0 1e-3 1e-6 1e-9 1e-12 1e-15]
Thank you in advance!

Accepted Answer

Birdman
Birdman on 1 Mar 2018
Edited: Birdman on 1 Mar 2018
P=1e3;
n=7;
for i=1:n
X(i)=P/10^3;
P=P/10^3;
end

More Answers (2)

Andrei Bobrov
Andrei Bobrov on 1 Mar 2018
n = 7;
P = 1e3;
X = P * 1e-3.^(0:n);
  2 Comments
Stephen23
Stephen23 on 1 Mar 2018
Edited: Stephen23 on 1 Mar 2018
+1 the simpler MATLAB way of doing this.
@Birdman: lots of users come here asking for "how to do XXX in a loop", and are surprised to learn that MATLAB has simpler, more efficient ways of doing things: they did not realize that loops were not required! It is entirely appropriate on this forum to point this out, and to show how.

Sign in to comment.


Prakash
Prakash on 1 Mar 2018
:-) Both answers are acceptable to me. Thanks!!

Community Treasure Hunt

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

Start Hunting!