For matrix A you cannot do: A.^2(:)
조회 수: 1 (최근 30일)
이전 댓글 표시
I have a matrix A=[1 2;3 4]. I want to sum the squares of the elements in the matrix. So I tried
sum(A.^2(:))
I cannot do this. The problem is A.^2(:). How do I solve this? Parenthesis around A.^2 does not help.
A workaround is
sum(reshape(A.^2,[],1))
Related to this is for example:
1+A(:)
This is OK. But this is not:
A+1(:)
Parenthesis around A+1 does not work.
댓글 수: 2
Paul
2024년 1월 28일
A=[1 2;3 4];
1 + A(:)
% A + 1(:) not sure what this is expected to do?
% maybe
A + 1
% or
A(:) + 1
채택된 답변
Matt J
2024년 1월 28일
편집: Matt J
2024년 1월 28일
You cannot apply ()-indexing to mathematical expressions, function calls, or literal constants, only to variables. So, in your case, you would do,
sum(A(:).^2)
Note that the result of other indexing expressions are considered variables for this purpose, so these are okay:
s.a={[5,1]}; s.b=[10,3,2];
s.a{1}(:)
s.b(:)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!