For loop pass in unique rows to function

7 ビュー (過去 30 日間)
Bewler
Bewler 2019 年 7 月 1 日
編集済み: Stephen23 2019 年 7 月 1 日
I have an array that is an X:4 double.
Column 1 of this array is the unique identifier labeled starting at 1 to n.
Example
[1,2.5,3,5 ; 1,3,4,5 ; 1,5,7,5 ; 2,4,5,6 ; 2,6,8,9]
I have a function that takes input normally as 3 columns (X,Y,Z).
I want to write a loop that takes the unique values of column 1 and pushes the rows unique(i:end of i, 2:4) for each unique i in the array that is the X:4
So from the above example it would first push rows 1:3,columns 2:4 to the function and then repeat the for loop to rows 4:5, columns 2:4 to the function.

採用された回答

Stephen23
Stephen23 2019 年 7 月 1 日
編集済み: Stephen23 2019 年 7 月 1 日
M = [1,2.5,3,5;1,3,4,5;1,5,7,5;2,4,5,6;2,6,8,9];
U = unique(M(:,1));
for k = 1:numel(U)
X = U(k)==M(:,1);
yourFunction(M(X,2:4))
end
  2 件のコメント
Bewler
Bewler 2019 年 7 月 1 日
Stephen, another beginner question related to this.
The output of the yourFunction is an XYZ array. Is there a way I could set the output of yourFunction(M(X,2:4)) combined with the k value? I want to create a new array from yourFunction that holds the k index in column 1 and the XYZ output of yourFunction to columns 2:4
I'm trying A = A(k,1) + yourFunction but I know it needs to somehow link A(k,1) + A(rows of yourFunction, 2:4).
Output [k,x,y,z,; k,x,y,z,; k,x,y,z,; k,x,y,z,;...]
Maybe I need to do
temporaryarray for the output of yourfunction,
then a [szrow] = size(temporaryarray),
then generate finalarray = finalarray concatenate vertically with finalarray(szrow,1) + concatenate horizontally with finalarray(temporaryarray,2:4)?
I'm just having a difficult time figuring out how to compartmentalize these steps to generate the new array.
Stephen23
Stephen23 2019 年 7 月 1 日
編集済み: Stephen23 2019 年 7 月 1 日
Here is one solution based around a cell array C that holds the output of each iteration, that should work for output matrices with three columns:
U = unique(M(:,1));
N = numel(U);
C = cell(1,N);
for k = 1:N
X = U(k)==M(:,1);
C{k} = yourFunction(M(X,2:4));
C{k}(:,4) = k;
end
A = vertcat(C{:});
A = A(:,[4,1:3]);
Note that you should not grow arrays inside a loop:

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

その他の回答 (0 件)

カテゴリ

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