How to insert values from a for loop into an array?
62 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Koalaclo
am 8 Dez. 2018
Beantwortet: Govardhan K
am 5 Mär. 2022
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!
0 Kommentare
Akzeptierte Antwort
madhan ravi
am 8 Dez. 2018
Bearbeitet: madhan ravi
am 8 Dez. 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 Kommentare
Rolwyn Cardoza
am 10 Nov. 2020
Bearbeitet: Rolwyn Cardoza
am 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
am 14 Feb. 2022
Thanks a lot! The pandas like 'no for-loop' operation reduced the calculation time from minutes to instant!
Weitere Antworten (1)
Govardhan K
am 5 Mär. 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
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!