필터 지우기
필터 지우기

Merging different arrays depending on condition

조회 수: 7 (최근 30일)
MiauMiau
MiauMiau 2017년 8월 28일
댓글: KL 2017년 8월 28일
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

채택된 답변

Stephen23
Stephen23 2017년 8월 28일
편집: Stephen23 2017년 8월 28일
"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
MiauMiau
MiauMiau 2017년 8월 28일
ah ok, my own written cell-array version just had a bug then. Many thanks!:)
KL
KL 2017년 8월 28일
Neat! +1

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by