Effacer les filtres
Effacer les filtres

Info

Cette question est clôturée. Rouvrir pour modifier ou répondre.

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

1 vue (au cours des 30 derniers jours)
Matt H
Matt H le 6 Mai 2011
Clôturé : MATLAB Answer Bot le 20 Août 2021
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

Réponses (5)

Teja Muppirala
Teja Muppirala le 7 Mai 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 le 7 Mai 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 le 6 Mai 2011
  2 commentaires
Matt H
Matt H le 6 Mai 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 le 6 Mai 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 le 6 Mai 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
  2 commentaires
Oleg Komarov
Oleg Komarov le 7 Mai 2011
Assuming b(i)-a(i) = k, for all i:
C = zeros(numel(a),b(1)-a(1))

Shravan Chandrasekaran
Shravan Chandrasekaran le 7 Mai 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.
  1 commentaire
Sean de Wolski
Sean de Wolski le 9 Mai 2011
DON'T CLEAR ALL!!!!! (five exclamation points should be enough)

Cette question est clôturée.

Community Treasure Hunt

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

Start Hunting!

Translated by