Creating an array within a for loop

I have a plotting function which gets the points to plot from a for loop, i.e.
for i=1:length(rat2ind)
ind = A(:,1)==A(rat2ind(i),1); % pick all the rat locs for rat i
plot(A(ind,2),A(ind,3),randcolor);axis([-0.5 7.5, -0.5 7.5]) % plot rat i trajectory
hold on;
end
but instead of plotting the points, I'd like to save the points in an (n,2) array. I tried this:
for i=1:length(rat2ind)
ind = A(:,1)==A(rat2ind(i),1);
H=vertcat(H,[A(ind,1),A(ind,2),A(ind,3)]);
end
but it gave me a variable which is definitely not what I needed as its twice as large as my original data (the data, and my actual goal isn't really relevant here)
Thanks for any help

4 Kommentare

Cedric
Cedric am 27 Jan. 2013
Bearbeitet: Cedric am 27 Jan. 2013
So in some sense you would like to order A by whatever key is stored in A(:,1), in a "key" order that is given by rat2ind ..?
Matt J
Matt J am 27 Jan. 2013
the data, and my actual goal isn't really relevant here
The data's size might be relevant when choosing an approach for you
This line is suspicious to me:
ind = A(:,1)==A(rat2ind(i),1);
are you sure that it is not:
ind = A(:,1) == rat2ind(i) ;
Timothy Russell
Timothy Russell am 28 Jan. 2013
changing this gives me exactly the same wrong answer...!

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Weitere Antworten (1)

Matt J
Matt J am 27 Jan. 2013
Bearbeitet: Matt J am 27 Jan. 2013

0 Stimmen

N=size(A,1);
map=double(bsxfun(@eq,sparse(A(:,1)),A(ratind,1).'));
ind=nonzeros( bsxfun(@times, (1:N).', map ) );
H=A(ind,1:3);

3 Kommentare

Timothy Russell
Timothy Russell am 28 Jan. 2013
This gives me the exact same array as my original code...which is very odd.
Matt J
Matt J am 29 Jan. 2013
Bearbeitet: Matt J am 29 Jan. 2013
Yeah, I see that now. My guess is that it's because, as Cedric pointed out, you probably really want to be comparing with ratind instead of A(ratind,1).
Timothy Russell
Timothy Russell am 2 Feb. 2013
Yeah you're right, sorry. The confusion came from trying to use exactly the same method in my plotting function, and forgetting what the variables actually represented. Thanks alot for the help, i'm actually starting to enjoy using matlab!_

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Programming finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by