How to insert values from a for loop into an array?

62 views (last 30 days)
I have to insert values from a for loop into an array, but can't get it to work as the loop variable starts at 0. I have tried the two following approaches, but neither work. Any advice or critisism would be very helpful.
Attempt 1 -
a = 500
b = 1000
for i=0:0.05:2
elements = a * i
area(i) = b + elements
end
Attempt 2
a = 500
b = 1000
area = [ ];
for i=0:0.5:2
elements = a*i
area = [b + elements]
end
Attempt 1 throws up an error message while attempt 2 just doesn't insert the values into an array. Any help would be appreciated. Thank you!

Accepted Answer

madhan ravi
madhan ravi on 8 Dec 2018
Edited: madhan ravi on 8 Dec 2018
Remember matlab index starts from one not from zero!
Without Loop (faster) :
a = 500
b = 1000
i=0:0.05:2;
elements = a * i ;
area = b + elements ;
With Loop :
First method:
a = 500;
b = 1000;
ctr=1;
i=0:0.05:2;
area=zeros(1,numel(i)); % preallocate
for i=i
elements = a * i ;
area(ctr) = b + elements ;
ctr=ctr+1;
end
Second method:
a = 500;
b = 1000;
ctr=1;
i=0:0.05:2;
area=zeros(1,numel(i)); % preallocate
for k=1:numel(i)
elements = a * i(k) ;
area(k) = b + elements ;
end
  4 Comments
Rolwyn Cardoza
Rolwyn Cardoza on 10 Nov 2020
Edited: Rolwyn Cardoza on 10 Nov 2020
Hello all, Please help me, I want to append all the values of q into a matrix and store it. The first row must contains all values of 'q' corresponding s1 total 6 rows and the coloumns must be equal to r = 10. Please help . Reach out if the question is not clear
clear
NeuberaData=[0.34 .48 .62 .76 .9 1.03 1.17 1.31 1.45 1.59 1.72;.66 .46 .36 .29 .23 .19 .14 .10 .075 .05 .03];
ND=NeuberaData;
qval=zeros(1,18);
Strength_set = ND(1,:)';
Notch_sense_const= ND(2,:)';
c=polyfit(Strength_set,Notch_sense_const,3);
for s= .3:.35:1.7
for r=1:.5:5
q= 1/ (1+(polyval(c,s))/sqrt(r));
qval(q)
end
end
Bharath Kumar Musuadhi Rajan
Thanks a lot! The pandas like 'no for-loop' operation reduced the calculation time from minutes to instant!

Sign in to comment.

More Answers (1)

Govardhan K
Govardhan K on 5 Mar 2022
a = 500;
b = 1000;
ctr=1;
i=0:0.05:2;
area=zeros(1,numel(i)); % preallocate
for i=i
elements = a * i ;
area(ctr) = b + elements ;
ctr=ctr+1;
end

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!