Compute the difference matix between a marix and another matrix in MATLAB
Mostra commenti meno recenti
Given a matrix A in matlab with:
A = [3,1;4,5;7,8]
and another matrix B which could be referred to as some reference points (each row is reference point that is to be compared to each row of A),
B = [1,1;1,2]
I need to compute a matrix C, such that
C = [4,5;25,18;85,72]
Where each row of C is the difference(squared L2 norm) between each row of A and the rows of B. One possible way to do this in MATLAB is to first create a zero matrix C, C = zeros(5,2), and then use double for-loops to fill in the appropriate value. Is there any other efficient/simpler way in MATLAB?
C = zeros(5,2)
for i = 1:rows
for j = 1:rows2
C(i,j) = (norm(A(i,:)-B(j,:)))^2
end
end
1 Commento
Pravin Jagtap
il 6 Feb 2020
Hello Jesujoba,
I think the way you have written the code is inconsistent with what you want to achieve. I would suggest that do the hand calculations for smaller numbers and make sure that your matrix 'C' is correct. Also, check the size of matrix C and the values of 'rows' and 'rows2' variables.
Risposta accettata
Più risposte (1)
Steven Lord
il 6 Feb 2020
You can eliminate one of your loops using the vecnorm function.
>> vecnorm(A-B(1, :), 2, 2).^2
ans =
4
25
85
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!