How to switch the indexing order

23 ビュー (過去 30 日間)
Maggie Chong
Maggie Chong 2023 年 6 月 15 日
移動済み: VBBV 2023 年 6 月 15 日
In matlab, the indexing for the find function numbers the matrix from top to bottom. However, for my code I need to run left to right. For exampe [1 ,2,3] etc.
Is there a different function I can use to achieve this?
  1 件のコメント
VBBV
VBBV 2023 年 6 月 15 日
移動済み: VBBV 2023 年 6 月 15 日

Use the transpose for your matrix and then apply find function to get the index for the actual matrix

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

採用された回答

the cyclist
the cyclist 2023 年 6 月 15 日
There's probably no way that isn't somewhat awkward, but here is a function that will convert a column-major index (which is what MATLAB uses) to a row-major linear index.
This assumes a 2-dimensional array, does no error checking, was untested on anything other than simple cases. (For example, didn't try empty arrays, etc.)
% Example use
% Some random matrix
M = rand(3,5);
% Use the function to find the 4th element in the first row, using row-major linear indexing
colMajorToRowMajor(4,M)
ans = 10
function rowMajorLinearIndex = colMajorToRowMajor(colMajorLinearIndex,M)
% Get input size
[MR,MC] = size(M);
% Convert
[cwr,cwc] = ind2sub([MC,MR],colMajorLinearIndex);
rowMajorLinearIndex = sub2ind(fliplr([MC,MR]),cwc,cwr);
end

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by