Creating array using other arrays and logical conditions.

조회 수: 1 (최근 30일)
Enkhzaya enkhtaivan
Enkhzaya enkhtaivan 2020년 8월 13일
댓글: Enkhzaya enkhtaivan 2020년 8월 13일
Hi, why does the below code return
Z = 0 0 0 0 1
X = [ -1 -2 3; -4 -5 -6];
Y = [ 3 3 3 ; 2 2 2];
M = ones(100);
Z (X > 0 & Y == 3) = M(X > 0 & Y ==3)
Only positive entry in X is at (1,3) position and Y = 3 at the first row of Y, so I expected something like 1 1 1 as the output.
I will appreciate if anyone can explain this to me, point me towards some tutorials about creating arrays in this way.

채택된 답변

Cris LaPierre
Cris LaPierre 2020년 8월 13일
편집: Cris LaPierre 2020년 8월 13일
You have specified the index using a single array rather than a value for rows and a value for columns. In addition, your array is logical (true/false). In this case, the indexing is using linear indexing. Let's look at your data to explain.
Your index is created using
(X > 0 & Y ==3)
The result of which is
ans =
2×3 logical array
0 0 1
0 0 0
MATLAB uses column-major layout by default. The top left element is 1, the bottom left is 2, the top middle is 3, etc. Your index, therefore, is referencing element 5.
The code M(X > 0 & Y ==3) is therefore using linear indexing to extract the 5th element of M. Since M is 100x100, it is hard to tell, but it returns M(5), which here is the same as M(5,1), which is 1 (everyting is 1 in M).
Now for the final part. You also use linear indexing to assign this value to Z. In essense, you code says "take the 5th element of M and assign it to the 5th element of Z". Since Z has not yet been defined, MATLAB creates it as a row vector and adds the extracted value of M to the 5th spot. Since values 1-4 have not been defined, they are added as 0, again because, to add a value to the 5th spot, elements 1-4 have to exist first.
Hope that helps.
  댓글 수: 1
Enkhzaya enkhtaivan
Enkhzaya enkhtaivan 2020년 8월 13일
This is a great explanation! Thanks and I might have some follow-up questions related to this, since I am working with much larger arrays in my actual code. But I do get the logic now.

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by