Storing data for "for loop"

3 ビュー (過去 30 日間)
Khang Nguyen
Khang Nguyen 2019 年 5 月 21 日
コメント済み: Star Strider 2019 年 5 月 21 日
Hi everyone,
for my L0 = [1 2 3 4 5], L10 = [2 3 4 5 6] L20 = [0 9 2 3 4] .... L200 = [2 3 4 5 6] (Up to 20 L values, just type random L for asking)
and x = [0:1:4]
I want to perform a polyfit function for 6th polynomial order for each L, with same x, but i do not want to each time type "polyfit(x,L0,6)" and then "polyfit(x,L20,6)
My question is : How can I make a for loop for this
I have tried L = [L0 L10 L20 ... L200],
but this way, it will store all values in one vector.
Please help ASAP !!
Thanks in advance

採用された回答

Star Strider
Star Strider 2019 年 5 月 21 日
Try something like this:
L0 = [1 2 3 4 5];
L10 = [2 3 4 5 6];
L20 = [0 9 2 3 4];
L = [L0; L10; L20];
x = 0:4;
n = size(L,2)-2;
for k = 1:size(L,1)
p(k,:) = polyfit(x,L(k,:),n);
end
This creates a matrix of row vectors in ‘L’. Note that I set ‘n’ to be 2 less than the vector lengths. A 6-order polynomial might be appropriate for your actual data, although it will crash here. (Please re-consider fitting a 6-order polynomial anyway.)
  2 件のコメント
Khang Nguyen
Khang Nguyen 2019 年 5 月 21 日
Thanks you so much. It works :)).
Star Strider
Star Strider 2019 年 5 月 21 日
As always, my pleasure!

サインインしてコメントする。

その他の回答 (2 件)

Josh
Josh 2019 年 5 月 21 日
You can store your L variables either as rows in a matrix:
% Create L matrix with a different L value in each row (I only put in three rows for simplicity)
L = [1, 2, 3, 4, 5; 2, 3, 4, 5, 6; 0, 9, 2, 3, 4];
% Create x value
x = 0:4;
% Create a result matrix; this will store the output of polyfit as separate rows:
order = 6;
results = zeros(size(L, 1), order + 1);
% Calculate the results
for i = 1 : size(L, 1)
results(i, :) = polyfit(x, L(i, :), order);
end
% The syntax L(i, :) returns the entire ith row of the matrix
  1 件のコメント
Khang Nguyen
Khang Nguyen 2019 年 5 月 21 日
I have tried your code, and it's only assign the value of the last L to the result matrices

サインインしてコメントする。


Geoff Hayes
Geoff Hayes 2019 年 5 月 21 日
Khang - don't create variables just for the sake of having variables. If all of your L arrays are of the same dimension, then just store them in a (for example) 20x5 matrix where each row corresponds to one of your (no longer needed) L variables. You would then iterate over each row and call polyfit on that row. For example,
for k=1:size(myData,1)
[p,S,mu] = polyfit(x,myData(k,:),6);
% store the results in an appropriately sized output matrix
end
where myData is your 20x5 array. If not all L arrays are of the same dimension, then just store all in a cell array.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by