how to find value in matrix based on specified location

조회 수: 11 (최근 30일)
Yu Li
Yu Li 2022년 12월 17일
편집: DGM 2022년 12월 17일
Hi:
I have a matrix and I want to cite the value at specified locaiton, the inputs is not specified row or colume, but the row-id and colume-id, for example:
A=[1,2,3,4;
5,6,7,8;
9,10,11,12;
13,14,15,16];
I want the cite the value at row=2, column=3, and row=3, colume=3
I tried command:
A([2,3],[3,3])
ans = 2×2
7 7 11 11
the output is a 2*2 matrix, instead of 7, 11.
is there anyway to make the output to be 7 and 11?
Thanks!
Yu

채택된 답변

DGM
DGM 2022년 12월 17일
편집: DGM 2022년 12월 17일
When you select A([2,3],[3,3]), you're selecting four points. It's easier to understand in this case:
A = [1,2,3,4;
5,6,7,8;
9,10,11,12;
13,14,15,16];
A([1 4],[1 4])
ans = 2×2
1 4 13 16
Note that you're selecting the intersection of the specified rows and columns. Since there are two each, there are four elements being selected.
The way around this ambiguity is to use linear indexing
A = [1,2,3,4;
5,6,7,8;
9,10,11,12;
13,14,15,16];
% convert to linear index
idx = sub2ind(size(A),[2,3],[3,3]);
% index into A
A(idx)
ans = 1×2
7 11

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by