필터 지우기
필터 지우기

Understanding the syntax meaning behind (:,)

조회 수: 5 (최근 30일)
Brendan Zotto
Brendan Zotto 2016년 9월 11일
댓글: Guillaume 2016년 9월 11일
Hey I am new to matlab and trying to do some math calculation to find the centroid of a cluster of data, however, I am running into syntax confusion. Can someone explain the (:,) part of this code to me, in both uses if possible. what exactly does it mean?
c(:, j) = mean(d(:, find(ind == j)), 2);
  댓글 수: 1
Guillaume
Guillaume 2016년 9월 11일
Others have already explained the meaning of the colon. I'll just note that the find call is completely unnecessary in the above,
c(:, j) = mean(d(:, ind == j), 2);
would produce exactly the same result slightly faster.

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

채택된 답변

James Tursa
James Tursa 2016년 9월 11일
편집: James Tursa 2016년 9월 11일
The colon : as a subscript simply means "all of the values" for this subscript. So e.g. c(:,j) is all the rows of the j'th column (i.e., the entire j'th column), and c(i,:) would be all of the columns of the i'th row (i.e., the entire i'th row). So the syntax
c(:,j) = etc
sets the j'th column of c to whatever is on the right hand side.
The syntax
d(:, find(ind == j))
is all of the rows of d that correspond to the column numbers that result from the find(ind==j). If only one ind equals j, then this will result in one column of d. If multiple values in ind equal j, then this will result in multiple columns of d. The last part of the syntax
mean(etc,2)
simply takes the mean of the first argument across the 2nd dimension. I.e., this averages the columns of the first argument.
So, taken as a whole, this syntax
c(:, j) = mean(d(:, find(ind == j)), 2);
will take the average of all of the columns of d where ind equals j, and assign that to the j'th column of c.
  댓글 수: 1
Brendan Zotto
Brendan Zotto 2016년 9월 11일
Both are great answers, I really appreciate this. Thanks!

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2016년 9월 11일
If c does not exist before the line is executed, then the code is equivalent to
temp = mean(d(1:size(d,1), find(ind == j)), 2);
c(1:length(temp), j) = temp;
If c does exist before the line is executed, then the code is equivalent to
c(1:size(c,1), j) = mean(d(1:size(d,1), find(ind == j)), 2);
In other words, when : appears by itself as an array index, it is equivalent to writing 1:end at that position, and in turn end is equivalent to size() of the matrix in that dimension . To put it another way, : appearing by itself stands for "all positions in this dimension"
  댓글 수: 1
Brendan Zotto
Brendan Zotto 2016년 9월 11일
Thanks for the answer, I appreciate it!

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

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by