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:
Arrary indexing with vectors ?

Subject: Arrary indexing with vectors ?

From: scho

Date: 26 Oct, 2010 14:55:30

Message: 1 of 3

I have a quick task in the following.

TBL = round(rand([256,256])*63)+1; % An arrary has random numbers between 1 to 64

M = 2048;

X = round(rand(M)*255)+1; % Vector of size M with random number between 1 to 256
Y = round(rand(M)*255)+1; % Vector of size M with random number between 1 to 256

Now, I want to make an array Z which is a vector of size Mx1, where each entry
has the one like,

Z(1) = TBL(X(1),Y(1));
Z(2) = TBL(X(2),Y(2));
....

Certainly, I can use for loop like,

for j=1:M
Z(j) = TBL(X(j),Y(j));
end

But, is there any way to do this with a simple vector operation ?

--

Subject: Arrary indexing with vectors ?

From: Matt J

Date: 26 Oct, 2010 15:12:03

Message: 2 of 3

"scho " <scho.2000@gmail.com> wrote in message <ia6q52$iaj$1@fred.mathworks.com>...
>
> Certainly, I can use for loop like,
>
> for j=1:M
> Z(j) = TBL(X(j),Y(j));
> end
>
> But, is there any way to do this with a simple vector operation ?

Yes.

Z= TBL( (Y-1)*255+X); %Use linear indexing

See also "doc SUB2IND" for a much slower solution.

Subject: Arrary indexing with vectors ?

From: Sean

Date: 26 Oct, 2010 15:14:04

Message: 3 of 3

"scho " <scho.2000@gmail.com> wrote in message <ia6q52$iaj$1@fred.mathworks.com>...
> I have a quick task in the following.
>
> TBL = round(rand([256,256])*63)+1; % An arrary has random numbers between 1 to 64
>
> M = 2048;
>
> X = round(rand(M)*255)+1; % Vector of size M with random number between 1 to 256
> Y = round(rand(M)*255)+1; % Vector of size M with random number between 1 to 256
>
> Now, I want to make an array Z which is a vector of size Mx1, where each entry
> has the one like,
>
> Z(1) = TBL(X(1),Y(1));
> Z(2) = TBL(X(2),Y(2));
> ....
>
> Certainly, I can use for loop like,
>
> for j=1:M
> Z(j) = TBL(X(j),Y(j));
> end
>
> But, is there any way to do this with a simple vector operation ?
>
> --

doc sub2ind


However, nothing you have here is going to work:
Z = TBL(sub2ind(size(TBL),X(1:2048),Y(1:2048)));

Why create the whole X,Y matrix, if you're only going to use the first column? Or are you trying to extract the diagonal of the M matrices?
Z = TBL(sub2ind(size(TBL),X(logical(eye(M))),Y(logical(eye(M)))));

Tags for 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