Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a matlab matrix to a vector

I want to get a vector of elements of a Matlab matrix at predefined locations. For example, I have the following

>> i = [1,2,3];
>> j = [1,3,4];
>> A = [1,2,3,4; 5,6,7,8; 9,10,11,12; 13,14,15,16]

A =

     1     2     3     4
     5     6     7     8
     9    10    11    12
    13    14    15    16

I want a vector that will give me the values of A at the locations correspongin to i,j. I tried

A(i,j)

ans =

     1     3     4
     5     7     8
     9    11    12

but this is not what I wanted. I want to get the following

>> [A(i(1),j(1)); A(i(2),j(2));A(i(3),j(3))]

ans =

     1
     7
    12

What is the matlab syntax for that? Please, avoid suggesting for loops or anything that is not in a vectorized form, as I need this to be done fast. Hopefully there will be some built-in function.

like image 881
D R Avatar asked Dec 19 '09 00:12

D R


People also ask

How do you make a vector in MATLAB?

You can create a vector both by enclosing the elements in square brackets like v=[1 2 3 4 5] or using commas, like v=[1,2,3,4,5]. They mean the very same: a vector (matrix) of 1 row and 5 columns. It is up to you.

How do you convert a vector to a matrix?

To convert a vector into matrix, just need to use matrix function. We can also define the number of rows and columns, if required but if the number of values in the vector are not a multiple of the number of rows or columns then R will throw an error as it is not possible to create a matrix for that vector.

How do you convert a vector to a vector in MATLAB?

Transpose. You can convert a row vector into a column vector (and vice versa) using the transpose operator ' (an apostrophe). Try the following MATLAB commands: [1 3 5] is a row vector, but the ' converts it into a column vector before the result is stored in the variable x.

How do I convert a matrix to an image in MATLAB?

I = mat2gray( A , [amin amax] ) converts the matrix A to a grayscale image I that contains values in the range 0 (black) to 1 (white). amin and amax are the values in A that correspond to 0 and 1 in I . Values less than amin are clipped to 0, and values greater than amax are clipped to 1.


1 Answers

to get it in the fastest way, use linear indexing:

A((j-1)*size(A,1)+i)

remember that MATLAB uses a column-major order.

like image 105
Amro Avatar answered Sep 29 '22 11:09

Amro