Split/slice vectors into sub-vectors and get their norms without a loop

158 views Asked by At

I have two vectors in MATLAB, vectorA and vectorB - both of equal lengths of 1280 elements. I want to split the vectors into sub-vectors of length 256, giving 5 sub-vectors.

Once I have the slices, say sliceA and sliceB, I need to perform norm on the two slices.

At the moment I have the following code:

for i = 1:N
    sliceA = vectorA(i:round(i*1280/N);
    sliceB = vectorB(i:round(i*1280/N));
    distance = distance+norm(sliceA,sliceB);
end
distance = distance/N;

Is it possible to remove the loop using some insane MATLAB logic?

1

There are 1 answers

1
Wolfie On BEST ANSWER

You can use reshape to make a 2D matrix of the slices

sliceA = reshape(vectorA, 256, 5);
sliceB = reshape(vectorB, 256, 5);

Then calculate the (Euclidean) norms and their sum for distance

norms = sqrt(sum((sliceA - sliceB).^2, 1));
distance = sum(norms)/5;

You can sum in either direction, depending which way you have reshaped the vector. Depending whether you want slices of 256 or 5, you may want to change the DIM argument of the sum to switch from summing down rows to summing across columns.

norms = sqrt(sum((sliceA - sliceB).^2, 1)); % Sums down rows, slices of 256
norms = sqrt(sum((sliceA - sliceB).^2, 2)); % Sums across cols, slices of 5

Note, you don't have to calculate both dimensions of the reshape function. As long as you choose a value which is a factor of the number of elements in your vector, you could do

sliceA = reshape(vectorA, 128, []); % correct number of slices of 128
sliceA = reshape(vectorA, [], N);   % This would use N how you are in the loop