Creating a loop for a matrix function

2 ビュー (過去 30 日間)
Kieran Phull
Kieran Phull 2019 年 11 月 27 日
回答済み: Katie 2019 年 11 月 27 日
Hi,
I have written a code that has carried out a function on the first two rows of a matrix and i want to write code that repeats this for the rest of the rows of the matrix (the matrix is interchangable).
  1 件のコメント
James Tursa
James Tursa 2019 年 11 月 27 日
Can you give us more details? If X is your matrix, then X(k,:) is the k'th row of the matrix and you should be able to use that in your calculations.

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

回答 (1 件)

Katie
Katie 2019 年 11 月 27 日
How you would write this code depends on how you want to do the function on the matrix rows:
  • Option 1: rows 1&2, then rows 3&4, then rows 5&6, and so on
  • Option 2: rows 1&2, rows 2&3, rows 3&4, and so on
For both cases, you can use a for loop and use the size() function to find the number of rows of the matrix you are using. size(mat,1) will give you the number of rows and size(mat,2) will give you the number of columns of the matrix "mat".
If you're looking to do option 1, you could do the following:
cnt=1;%index for a matrix "x" to store all the results in, that isn't incremented with the loop
for i=1:2:size(mat,1)%loop through the rows of the matrix at increments of 2
if i+1<=size(mat,1) %check to make sure you won't go past the last row
x(cnt)=fcn(mat(i,:),mat(i+1,:))%doing the function on the current row of the matrix and the next row
cnt=cnt+1;
end
end
For option 2, you would make some slight changes to the above code, mainly not incrementing the for loop by 2 and not needing to check to make sure you don't try to index rows of the matrix that don't exist.
for i=1:size(mat,1)-1%loop through the rows of the matrix, using size-1 makes sure you don't go past the last row
x(i)=fcn(mat(i,:),mat(i+1,:))%doing the function on the current row of the matrix and the next row
end

カテゴリ

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