Filter löschen
Filter löschen

How can I populate the rows of a difference matrix without using a for loop?

2 Ansichten (letzte 30 Tage)
I am creating Matlab code to construct the following matrix:
In my data, x and y are 101-dimensional real vectors and N is a vector of six real numbers. My Matlab implementation is
% Real inputs of length 101 for x,y and length 6 for X,Y
x = rand(1,101);
y = rand(1,101);
X = rand(6,1);
Y = rand(6,1);
n = length(x);
N = length(X);
G = zeros((N-1),2,n);
% Distance calculation
d = @(k) sqrt((X(k) - x).^2 + (Y(k) - y).^2); % L2 Norm / Euclidean distance
xdiff = @(k) (((X(1) - x) ./ d(1)) - ((X(k+1) - x) ./ d(k+1)));
ydiff = @(k) (((Y(1) - y) ./ d(1)) - ((Y(k+1) - y) ./ d(k+1)));
GBlock = @(k) [xdiff(k) ydiff(k)];
% This seems inefficient - is there a better alternative?
Z = all(G>=0,2);
for k = 1:size(G,1)
if Z(k)
G(k,:) = GBlock(k);
end
end
Creating Gblock followed by a for loop seems inefficient. Is there a way to vectorize this code and avoid writing a for loop?
  3 Kommentare
Matthew Kehoe
Matthew Kehoe am 17 Okt. 2023
Bearbeitet: Matthew Kehoe am 18 Okt. 2023
Yes, I incorrect indexed two locations of x and y. I have updated my original question.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Matt J
Matt J am 16 Okt. 2023
Bearbeitet: Matt J am 16 Okt. 2023
X=X(:);
Y=Y(:);
x=reshape(x,1,1,[]);
y=reshape(y,1,1,[]);
d=hypot( X - x , Y - y );
Diff=@(U,u) ((U(1)-u)./d(1,1,:)) - ((U(2:end) - u) ./ d(2:end,1,:));
G=[Diff(X,x), Diff(Y,y)];

Weitere Antworten (0)

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Produkte


Version

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by