Make matrix from input size
Show older comments
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?
Accepted Answer
More Answers (2)
James Tursa
on 30 May 2015
Edited: James Tursa
on 30 May 2015
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 Comments
Millone
on 30 May 2015
Walter Roberson
on 30 May 2015
In that case use a nested for loop.
Millone
on 30 May 2015
Walter Roberson
on 30 May 2015
Then you aren't using a nested for. A nested for is like
for J = 1 : 17
for K = 53 : 88
...
end
end
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!