Combining arrays to form indices

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

One way...
C=cell2mat(arrayfun(@colon,A,B,'uniformoutput',false));

1 Comment

Thank you! That works perfectly for my application.

Sign in to comment.

More Answers (2)

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

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.

x(B+1)=-1;
x(A)=1;
out = A(1):B(end)+1;
out = out(cumsum(x)>0);

Tags

Asked:

on 21 Feb 2014

Answered:

on 21 Feb 2014

Community Treasure Hunt

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

Start Hunting!