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!