How can I create an array with a for loop?

Hi I’m trying to create an array of values that are output from a function. The function goes from -20 to 50 but I can’t create an array that large so I’m confused on what to do. The attached picture is what I have so far and it’s not working.
% code
clear all;
close all;
A = zeros(1:70);
for m = 1:70;
n = -50:20;
X = power(0.8,n)
A(m) = X
end
stem(n,arrayofA(n))

댓글 수: 1

Do not use the accepted answer: a loop is NOT required:
n = -50:20;
A = power(0.8,n);

댓글을 달려면 로그인하십시오.

답변 (2개)

Torsten
Torsten 2018년 3월 12일

2 개 추천

A = zeros(1,71);
n = -50:20;
A = power(0.8,n)

댓글 수: 1

Jos (10584)
Jos (10584) 2018년 3월 12일
This is preferred over the solution with a for-loop. However, there is no need to initialise A with zeros first, since you overwrite it at the third line.

댓글을 달려면 로그인하십시오.

Birdman
Birdman 2018년 3월 12일
편집: Birdman 2018년 3월 12일

1 개 추천

Try this:
A=zeros(1,70);n=-50:20;
for m=1:numel(n)
A(m)=power(0.8,n(m));
end
stem(n,A)

댓글 수: 5

Paige Coffeen
Paige Coffeen 2018년 3월 12일
This one looks like it worked! Can you explain what is the m=1:numel(n) function doing? That seems to be the connecting factor I needed.
Thank you!!
Birdman
Birdman 2018년 3월 12일
It is the condition for the loop to be operated. m starts at 1, incremented by 1 and the loop is over when m is equal to the number of elements in n vector, which is 71. At each step, the statement in for loop is executed and the result is stored in A array.
Jos (10584)
Jos (10584) 2018년 3월 12일
As Torsten showed, A = power(0.8,n) would do. No need for a for-loop
y = zeros(1,12);
for i = 1:12
y(i+1) = y(i) + ((5 - (4/50)*y(i)));
end
y
y = 1×13
0 5.0000 9.6000 13.8320 17.7254 21.3074 24.6028 27.6346 30.4238 32.9899 35.3507 37.5227 39.5209
x = zeros(1,10);
for i = 10:-1:2
x(i-1) = x(i) + ((5 + (4/50)*x(i)));
end
x
x = 1×10
62.4378 53.1831 44.6140 36.6796 29.3330 22.5306 16.2320 10.4000 5.0000 0
Good Day,
May I ask how can I insert the start and stop variable on above code? for example I want to start in 17 to 30 or 15 to 2 with decrementing step.
Thanks and Regards,
Dennis
You should ask your own question for that.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2018년 3월 12일

댓글:

2021년 8월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by