How to insert values from a for loop into an array?
62 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
madhan ravi
2018-12-8
编辑:madhan ravi
2018-12-8
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 个评论
Rolwyn Cardoza
2020-11-10
编辑:Rolwyn Cardoza
2020-11-10
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
2022-2-14
Thanks a lot! The pandas like 'no for-loop' operation reduced the calculation time from minutes to instant!
更多回答(1 个)
Govardhan K
2022-3-5
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!