Combining arrays to form indices

2 views (last 30 days)
Robert
Robert on 21 Feb 2014
Answered: Andrei Bobrov on 21 Feb 2014
I'm wondering if there's a method to combine 2 linear arrays for matrix indexing purposes.
For example given the arrays:
A = [1 10 15 25 35]
B = [5 13 18 31 52]
How would one create an indexing array such as:
C = [1:5 10:13 15:18 25:31 35:52]
Hopefully that makes sense, thanks for the help!

Accepted Answer

dpb
dpb on 21 Feb 2014
One way...
C=cell2mat(arrayfun(@colon,A,B,'uniformoutput',false));
  1 Comment
Robert
Robert on 21 Feb 2014
Thank you! That works perfectly for my application.

Sign in to comment.

More Answers (2)

Chad Greene
Chad Greene on 21 Feb 2014
I like dpb's solution. My slower, clunkier solution would have required a loop:
A = [1 10 15 25 35];
B = [5 13 18 31 52];
m = 1;
for n = 1:length(A)
d = A(n):B(n);
C(m:m+length(d)-1) = d;
m = m+length(d);
end
  1 Comment
dpb
dpb on 21 Feb 2014
The thing in coming up w/ such solutions is to remember that Matlab operators like : are implemented as functions syntactically so that there's always a functional name form (here colon, of course) to use where need a function handle or the like. It's always easier to think of with "real" functions like mean, say, whereas it's easy to forget about the symbols having alias names because they're not used as often.

Sign in to comment.


Andrei Bobrov
Andrei Bobrov on 21 Feb 2014
x(B+1)=-1;
x(A)=1;
out = A(1):B(end)+1;
out = out(cumsum(x)>0);

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!