Merging different arrays depending on condition

22 views (last 30 days)
MiauMiau
MiauMiau on 28 Aug 2017
Commented: KL on 28 Aug 2017
Hi
I have a following vector called cases as follows:
cases = [1,4,4,3,1,2,2,4,3,4,4,...];
Additionally, I have four arrays Array1 to Array4.
Now I want to construct a new Array, where the elements of this new array are picked from the Array1,...,Array4 depending on what the "cases" array indicates. So for instance, the first element of cases is "1" which means to pick from Array 1 (and I would like to do this in the right order, so I pick the first element of Array1). Then the second element of cases is a "4", so now I want to sample from Array 4, again the first element. The next element of cases is again "4", now I pick the second element of Array4 and so on. How can I do that effectively? The only thing which comes to my mind is to loop with ifelse loops, but that seems rather not so straightforward. Thanks

Accepted Answer

Stephen
Stephen on 28 Aug 2017
Edited: Stephen on 28 Aug 2017
"How can I do that effectively?"
Like always in MATLAB, using indexing is going to be simple and efficient, and storing data in lots of separate matrices just makes code complicated, so the first thing we will do is put all of the data into one cell array, then the solution is simple:
>> cases = [1,4,4,3,1,2,2,4,3,4];
>> C = {101:110,201:210,301:310,401:410};
>> arrayfun(@(c,x)C{c}(x),cases,1:numel(cases))
ans =
101 402 403 304 105 206 207 408 309 410
>>
If the matrices are the same size then you could also put them into one numeric array, which would make the code a bit more efficient:
>> M = [101:110;201:210;301:310;401:410]
M =
101 102 103 104 105 106 107 108 109 110
201 202 203 204 205 206 207 208 209 210
301 302 303 304 305 306 307 308 309 310
401 402 403 404 405 406 407 408 409 410
>> M(sub2ind(size(M),cases,1:numel(cases)))
ans =
101 402 403 304 105 206 207 408 309 410
>>
  8 Comments

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by