mad
mad

Reputation: 2789

sub2ind all x and y coordinates of a matrix

I am a quite newbie on matlab and i have a simple issue that is disturbing me,

I want to know if its possible to covert all the subscripts of a matrix to linear indices.

when using SUB2IND i must inform de x and y coordinates, but i want to convert all at the same time.

i can use function FIND which returns two vectors x and y and this way i can use SUB2IND succesfully, but FIND only returns the x and y coordinates of nonzero elements.

is there a smart way to do this?

Upvotes: 0

Views: 1484

Answers (2)

horchler
horchler

Reputation: 18484

If you want all of the elements of an array A as linear subscripts, this can be done simply via:

IND = 1:numel(A);

This works for any size or dimension array.

More on array indexing in Matlab, including the difference between linear indexing and logical indexing. When you use find you're essentially using logical indexing to obtain linear indexing. The find function can be used to reliably obtain all of your linear indices, via IND = find(A==A);, but this is horrendously inefficient.

Upvotes: 1

bla
bla

Reputation: 26069

you don't need to convert, just use a single number \ 1-D vector when accessing elements of your matrix. For example, given a 5x5 matrix M

M=magic(5);

you can access the last element using M(5,5) or using M(25) ...

similarly M(21:25) will give you the info of M(1,5),M(2,5),...M(5,5).

Upvotes: 1

Related Questions