필터 지우기
필터 지우기

Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

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

조회 수: 1 (최근 30일)
Matt H
Matt H 2011년 5월 6일
마감: MATLAB Answer Bot 2021년 8월 20일
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

답변 (5개)

Teja Muppirala
Teja Muppirala 2011년 5월 7일
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 2011년 5월 7일
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 2011년 5월 6일
  댓글 수: 2
Matt H
Matt H 2011년 5월 6일
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 2011년 5월 6일
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 2011년 5월 6일
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 2011년 5월 7일
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.

이 질문은 마감되었습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by