Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Access data within a Matrix

Subject: Access data within a Matrix

From: Jose Miguel

Date: 14 Jun, 2012 10:03:07

Message: 1 of 3

Dear all,

In relation with my previous post, it would be enough to solve the following case.

I have a m x n matrix named data:

I have two vectors a and b containing the row and column indexes to access.
Obviously they have the same size
Would it be possible to access the data directly, without a loop?

data=[4 5 3; 5 2 1;4 5 2];
a=[2 1];
b=[3 2];

I'd like to obtain the result in a vector way, result = [1 5]
The length of a and b is normally very long, so the solution result = [data(a(1),b(1)) data(a(2),b(2))], would not be valid

Thank you very much for your help,
Regards
Jose

Subject: Access data within a Matrix

From: Nasser M. Abbasi

Date: 14 Jun, 2012 10:16:31

Message: 2 of 3

On 6/14/2012 5:03 AM, Jose Miguel wrote:
> Dear all,
>
> In relation with my previous post, it would be enough to solve the following case.
>
> I have a m x n matrix named data:
>
> I have two vectors a and b containing the row and column indexes to access.
> Obviously they have the same size
> Would it be possible to access the data directly, without a loop?
>
> data=[4 5 3; 5 2 1;4 5 2];
> a=[2 1];
> b=[3 2];
>
> I'd like to obtain the result in a vector way, result = [1 5]
> The length of a and b is normally very long, so the solution
>result = [data(a(1),b(1)) data(a(2),b(2))], would not be valid
>
> Thank you very much for your help,
> Regards
> Jose

-----------------
data=[4 5 3; 5 2 1;4 5 2];
a=[2 1];
b=[3 2];
data(sub2ind(size(data),a,b))
---------------

ans =

      1 5


--Nasser

Subject: Access data within a Matrix

From: Jose Miguel

Date: 14 Jun, 2012 11:27:07

Message: 3 of 3

Nasser,
 
Thank you very much for such an elegant solution.

Would it be possible to apply an analogue solution for a 4 dimension variable.

size(var)

ans =

           1 1460 256 512

I want to select the all the data for the 1st and 2nd dimension and 4 sets of data from the 3rd and 4th dimension.
I have four indexes in a vector "a" telling the indexes of the 3rd dimension and another vector with four indexes "b" telling the indexes of the 4th dimension.

The idea is to do:
data = var(:, :, a, b), obviously this instruction doesn't work

Would it be possible to do it with just one access to the data?
The problem of using a loop is that the elapsed time is multiply x 4

Thank you very much,
Regards
Jose

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us