Meaning of the if statement

조회 수: 2 (최근 30일)
Muhtasim Haque Nahian
Muhtasim Haque Nahian 2021년 4월 19일
댓글: Muhtasim Haque Nahian 2021년 5월 9일
function z = in_prod(x,y)
if size(x,2)==size(y,1)
z=x*y
else
z = "The inner dimensions are " + size(x,2) + " and " + size(y,1) + ". Matrix multiplication is not possible";
end
  • Can anyone explain me the meaning of this if statement please?
  • More specifically, why size(x,2) and size(y,1)? Why not size(x,any other value)?
TIA!
  댓글 수: 1
Stephen23
Stephen23 2021년 4월 19일
"More specifically, why size(x,2) and size(y,1)?"
Because matrix multiplication is only defined when those dimensions are equal:
"Why not size(x,any other value)?"
Because matrix multiplication is only defined for 2D matrices.

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

답변 (1개)

David Fletcher
David Fletcher 2021년 4월 19일
편집: David Fletcher 2021년 4월 19일
The if statement is checking that the number of columns in x (the number two in the argument of size is specifying that the function returns the number of columns) matches the number of rows in y (the number one in the argument of size is specifying that the function returns the number of rows). This ensures that matrix multiplication can be applied to x and y. If the inner dimensions do not match, the matrices cannot be multiplied.
  댓글 수: 1
Muhtasim Haque Nahian
Muhtasim Haque Nahian 2021년 5월 9일
Thanks for the explanation! It helped

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

카테고리

Help CenterFile Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by