Need help using colon operator with multiple matrices - I'm really close to being loopless!
Info
This question is closed. Reopen it to edit or answer.
Show older comments
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
Answers (5)
Teja Muppirala
on 7 May 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
on 7 May 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
on 6 May 2011
0 votes
Bruno's mcolon on the FEX:
2 Comments
Matt H
on 6 May 2011
Sean de Wolski
on 6 May 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
on 6 May 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 Comments
Oleg Komarov
on 6 May 2011
Why the cell Matt?
Oleg Komarov
on 7 May 2011
Assuming b(i)-a(i) = k, for all i:
C = zeros(numel(a),b(1)-a(1))
Shravan Chandrasekaran
on 7 May 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 Comment
Sean de Wolski
on 9 May 2011
DON'T CLEAR ALL!!!!! (five exclamation points should be enough)
This question is closed.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!