How to slice a two-dimensional array to get a one-dimensional array

9 ビュー (過去 30 日間)
Donald Liu
Donald Liu 2018 年 2 月 27 日
回答済み: drummer 2020 年 10 月 2 日
Hi! This seems to be a simple question but I couldn't find its answer after some searching. Let
a = rand(5, 4); i = [2 4 3]; j = [1 2 3];
How do I write a slicing expression to yield the one-dimensional array [a(2, 1), a(4, 2), a(3, 3)]? The expression a(i, j) yields a 3x3 matrix, which is not what I wanted.
Thanks!

回答 (2 件)

Donald Liu
Donald Liu 2018 年 2 月 27 日
I just found a solution: a(i + (j-1)*4). Are there better answers?
Thanks!

drummer
drummer 2020 年 10 月 2 日
Well, this is a specific suggestion for this case.
You might implement some sort of loop for bigger cases.
a = rand(5, 4)
i = [2 4 3];
j = [1 2 3];
b = [a(i(1), j(1)) a(i(2), j(2)) a(i(3), j(3))]
So you're basically creating a array b with size (1, 3), calling each element from a by passing the indexes of i and j.
If that works, please accept the answer =)
Cheers.

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by