I have an input of zeros n x n and I would like to output a matrix with an index like this:
function [ out ] = test3( mat )
[r c]= size(mat)
end
for input [0 0 0; 0 0 0] output [1 1; 1 2; 1 3; 2 1; 2 2; 2 3]
for input [0 0 0 0; 0 0 0 0; 0 0 0 0] output [1 1; 1 2; 1 3; 1 4; 2 1; 2 2; 2 3; 2 4; 3 1; 3 2; 3 3; 3 4]
and so on for all size of 0 matrix input. I tried something like
out=[1:r 1:c]
But I get the wrong output. How can I achieve something like this?

 採用された回答

Stephen23
Stephen23 2015 年 5 月 30 日
編集済み: Stephen23 2015 年 5 月 30 日

0 投票

If you want all pairs of subscript indices, then you can use ind2sub:
>> mat = zeros(2,3)
mat =
0 0 0
0 0 0
>> [R,C] = ind2sub(size(mat),1:numel(mat));
>> [R;C]'
ans =
1 1
2 1
1 2
2 2
1 3
2 3
And use sortrows if you really need that exact order:
>> sortrows([R;C]')
ans =
1 1
1 2
1 3
2 1
2 2
2 3
Note that in MATLAB there are three main ways of indexing, and using subscript indices is not the most efficient: logical indexing is usually the fastest indexing method.

その他の回答 (2 件)

James Tursa
James Tursa 2015 年 5 月 30 日
編集済み: James Tursa 2015 年 5 月 30 日

1 投票

doc ndgrid
Look at combining the results with your 1:r and 1:c inputs.
EDIT:
Using your two inputs of 1:r and 1:c, it appears you want to get all combinations of pairs of them. So ndgrid can be used to do this.
[X,Y] = ndgrid(1:r,1:c);
out = [X(:) Y(:)];
The (:) notation turns a variable into a column vector.

4 件のコメント

Millone
Millone 2015 年 5 月 30 日
Thanks but that looks quite complex for me. I am just starting using Matlab on my own.
Walter Roberson
Walter Roberson 2015 年 5 月 30 日
In that case use a nested for loop.
Millone
Millone 2015 年 5 月 30 日
Thanks a lot. But for input [0 0; 0 0] I should have 1 1; 1 2; 2 1; 2 2 and I get instead 1 1; 1 2; 1 3; 1 4;
Walter Roberson
Walter Roberson 2015 年 5 月 30 日
Then you aren't using a nested for. A nested for is like
for J = 1 : 17
for K = 53 : 88
...
end
end

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

Andrei Bobrov
Andrei Bobrov 2015 年 5 月 30 日

1 投票

sortrows(fullfact(size(mat)),1)

1 件のコメント

Stephen23
Stephen23 2015 年 5 月 30 日
+1 An excellent solution.
Note that fullfact requires the Statistics Toolbox.

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

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

タグ

質問済み:

2015 年 5 月 30 日

コメント済み:

2015 年 5 月 30 日

Community Treasure Hunt

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

Start Hunting!

Translated by