For matrix A you cannot do: A.^2(:)

1 vue (au cours des 30 derniers jours)
Eric
Eric le 28 Jan 2024
Modifié(e) : Catalytic le 28 Jan 2024
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 commentaires
Paul
Paul le 28 Jan 2024
A=[1 2;3 4];
1 + A(:)
ans = 4×1
2 4 3 5
% A + 1(:) not sure what this is expected to do?
% maybe
A + 1
ans = 2×2
2 3 4 5
% or
A(:) + 1
ans = 4×1
2 4 3 5
Eric
Eric le 28 Jan 2024
The same as 1+A(:).

Connectez-vous pour commenter.

Réponse acceptée

Matt J
Matt J le 28 Jan 2024
Modifié(e) : Matt J le 28 Jan 2024
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}(:)
ans = 2×1
5 1
s.b(:)
ans = 3×1
10 3 2

Plus de réponses (1)

Catalytic
Catalytic le 28 Jan 2024
Modifié(e) : Catalytic le 28 Jan 2024
A=[1 2;3 4];
sum(A(:).^2)
ans = 30
vecnorm(A(:))^2
ans = 30
norm(A,'fro')^2
ans = 30

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by