Combining arrays to form indices
2 views (last 30 days)
Show older comments
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!
0 Comments
Accepted Answer
More Answers (2)
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
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.
Andrei Bobrov
on 21 Feb 2014
x(B+1)=-1;
x(A)=1;
out = A(1):B(end)+1;
out = out(cumsum(x)>0);
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!