Borrar filtros
Borrar filtros

Info

La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.

Need help using colon operator with multiple matrices - I'm really close to being loopless!

1 visualización (últimos 30 días)
Simplified problem is: a=[1 2 3]; b=[4 5 6]; How can I get to: c=[1 2 3 4; 2 3 4 5; 3 4 5 6];
I've tried the obvious, a:b will return only c=[1 2 3 4]; Any ideas?
Many thanks, - Matt

Respuestas (5)

Teja Muppirala
Teja Muppirala el 7 de Mayo de 2011
If you know that it's going to end up being a rectangular matrix like in your example, then the (b-a) all have to be the same:
if all( (b-a) == (b(1)-a(1)) )
bsxfun(@plus,a',0:(b(1)-a(1)))
end

Andrei Bobrov
Andrei Bobrov el 7 de Mayo de 2011
more variant
a=[1 2 3];
b=[4 5 6];
c = [a b];
c = c(cumsum([1:4; ones(2,4)]));
or in this case, just
c = cumsum([1:4; ones(2,4)])
more
c1 = repmat(min(a):max(b),length(a),1)';
c = reshape(c(ones(size(c1,1),1)*a<=c1&c1<=ones(size(c1,1),1)*b),[],length(a))';

Sean de Wolski
Sean de Wolski el 6 de Mayo de 2011
  2 comentarios
Matt H
Matt H el 6 de Mayo de 2011
Not sure I like this option, I feel like I'd be better off (crunch time wise) with a for loop.
Sean de Wolski
Sean de Wolski el 6 de Mayo de 2011
Then go with a for loop.
I think this is the thread that started mcolon:
http://www.mathworks.com/matlabcentral/newsreader/view_thread/298813

Matt Fig
Matt Fig el 6 de Mayo de 2011
I am not sure if this is in the above thread or not. But perhaps the simplest FOR loop version is this:
a=[1 2 3];
b=[4 5 6];
C = cell(1,length(a));
for ii = 1:length(a)
C{ii} = a(ii):b(ii);
end
C = [C{:}]
But, like Sean de, I would use the MEX version if speed due to very large a and b is at all a concern.
EDIT In response to Oleg's comment.
Oleg makes the point that my code above is not the simplest FOR loop implementation. I guess the urge to pre-allocate is too strong in me! This is simpler, though slower on my machine for larger a and b:
a=[1 2 3];
b=[4 5 6];
C = []
for ii = 1:length(a)
C = [C a(ii):b(ii)];
end

Shravan Chandrasekaran
Shravan Chandrasekaran el 7 de Mayo de 2011
Hi Matt,
This works
clear all;
clc;
a=[1 2 3]
b=[4 5 6]
A=[a b]
for i=1:1:3
for j=1:1:4
AA(i,j)=A(1,i+(j-1));
end
end
AA
Regards, Shravan.

La pregunta está cerrada.

Community Treasure Hunt

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

Start Hunting!

Translated by