0

I have an array in Matlab, let say of (256, 256). Now i need to build a new array of dimensions (3, 256*256) containing in each row the value, and the index of the value in the original array. I.e:

test = [1,2,3;4,5,6;7,8,9]

test =

 1     2     3
 4     5     6
 7     8     9

I need as result:

[1, 1, 1; 2, 1, 2; 3, 1, 3; 4, 2, 1; 5, 2, 2; and so on]

Any ideas? Thanks in advance!

2 Answers 2

3

What you want is the output of meshgrid

[C,B]=meshgrid(1:size(test,1),1:size(test,2))
M=test;
M(:,:,2)=B;
M(:,:,3)=C;
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry, I am new at matlab and I think I messed up with the question. Let me rephrase, I have an image in a matrix of 256x256 and need to get a "list" of the images coordinates along with the value in the coordinate. So, if position 1,1 of the matrix contains the value 145, then first row of the resulting array will be [145, 1, 1] and so on.
1

here's what i came up with

test = [1,2,3;4,5,6;7,8,9]; % orig matrix

[m, n] = size(test); % example 1, breaks with value zero elems
o = find(test);
test1 = [o, reshape(test, m*n, 1), o]

Elapsed time is 0.004104 seconds.

% one liner from above
% (depending on data size might want to avoid dual find calls)
test2=[ find(test) reshape(test, size(test,1)*size(test,2), 1 ) find(test)]

Elapsed time is 0.008121 seconds.

[r, c, v] = find(test); % just another way to write above, still breaks on zeros
test3 = [r, v, c]

Elapsed time is 0.009516 seconds.

[i, j] =ind2sub([m n],[1:m*n]); % use ind2sub to build tables of indicies
                                % and reshape to build col vector
test4 = [i', reshape(test, m*n, 1), j']

Elapsed time is 0.011579 seconds.

test0 = [1,2,3;0,5,6;0,8,9]; % testing find with zeros.....breaks
% test5=[ find(test0) reshape(test0, size(test0,1)*size(test0,2), 1 ) find(test0)] % error in horzcat

[i, j] =ind2sub([m n],[1:m*n]); % testing ind2sub with zeros.... winner
test6 = [i', reshape(test0, m*n, 1), j']

Elapsed time is 0.014166 seconds.

Using meshgrid from above: Elapsed time is 0.048007 seconds.

1 Comment

So, if you dont have zeros, I'd recommend using find. Otherwise ind2sub? Keep in mind this for a realllly small dataset. You should tic toc to find out how it scales with your data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.