Indexing a matrix with an array

조회 수: 3 (최근 30일)
John Jönsson
John Jönsson 2020년 2월 23일
댓글: Stephen23 2020년 2월 23일
Let's say I have a 4x4 matrix A. I can then get the item in place [2,3] by typing A(2,3).
Now let's say I have an array I=[2,3]. I would like to be able to write something like A(I) to get the same result as above. How could I do that?
Thanks.

채택된 답변

Stephen23
Stephen23 2020년 2월 23일
편집: Stephen23 2020년 2월 23일
Use a cell array, e.g.:
C = {2,3}; % use NUM2CELL(I) if required.
A(C{:})
Tested:
>> A = rand(4,4)
A =
0.340974 0.252464 0.596849 0.800738
0.064510 0.270160 0.242550 0.518083
0.546270 0.318667 0.581832 0.409444
0.814609 0.675596 0.588558 0.353607
>> C = {2,3};
>> A(C{:})
ans = 0.24255
  댓글 수: 2
John Jönsson
John Jönsson 2020년 2월 23일
Thank you very much. Is there a function similar to zeros(1,n) or ones(1,n) where I can make C = {0,0,0,0,0,...} of length n? And what is C called? Do we call it a set?
Stephen23
Stephen23 2020년 2월 23일
"Is there a function similar to zeros(1,n) or ones(1,n) where I can make C = {0,0,0,0,0,...} of length n?"
Here are two ways:
C = repmat({0},1,n)
C = num2cell(zeros(1,n))
"And what is C called?"
a cell array:
MATLAB does not have a "set" data type:

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by