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

62 visualizzazioni (ultimi 30 giorni)
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!

Risposta accettata

madhan ravi
madhan ravi il 8 Dic 2018
Modificato: madhan ravi il 8 Dic 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 Commenti
Rolwyn Cardoza
Rolwyn Cardoza il 10 Nov 2020
Modificato: Rolwyn Cardoza il 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!

Accedi per commentare.

Più risposte (1)

Govardhan K
Govardhan K il 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

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by