Vectorize comparing a column vector in a matrix to all other vectors in the matrix.
Afficher commentaires plus anciens
Hello,
I am trying to take the difference between a column in a matrix to the rest of the matrix but I am trying to do it without using a loop is this possible? Additionally, would doing it without the loop be more efficient, or would you have to spend a bunch of time in overhead to set it up so that you can do it vectorized?
Example Code:
% Variable Definitions
A.a = rand(10,11);
A.b = rand(10,11);
A.c = rand(10,11);
% Memory Pre-allocation
d = zeros(10,11);
e = zeros(1,11);
% Loop
for i = 1:size(A.a,2)
a = A.a - A.a(:,i);
b = A.b - A.b(:,i);
c = A.c - A.c(:,i);
d = sqrt(a.^2 + b.^2 + c.^2);
e(i) = max(max(d));
end
% The line below shows that knowing the column
% of that the maximum values are in is important.
[~, index] = min(e);
%% Alternatively it could look something like the below
for i = 1:size(A.a,2)
a(:,:,i) = A.a - A.a(:,i);
b(:,:,i) = A.b - A.b(:,i);
c(:,:,i) = A.c - A.c(:,i);
end
d = sqrt(a.^2 + b.^2 +c.^2);
e = max(max(d));
% But I want to do it without having to do the loop? Is this possible.
Réponse acceptée
Plus de réponses (1)
Michael
le 23 Juin 2022
You can use repmat.m to make a matrix of the same size.
a = A.a - repmat(A.a(:,1),1,size(A.a,2))
b = A.b - repmat(A.b(:,1),1,size(A.b,2))
c = A.c - repmat(A.c(:,1),1,size(A.c,2))
Catégories
En savoir plus sur Matrix Indexing dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!