0
votes

I have a cell array (data) containing 3 matrices, each with 18 columns and 108021, 108022 and 108021 rows respectively. I need to calculate the Euclidean distance between columns 13, 14 and 15, 16 for each matrix and I am using the following code:

for m = 1:length(data)
 for i = 1:length(data{m})
  distance(i) = norm(data{m}(i,13:14)-data{m}(i,15:16));
 end
end

It works except for the last matrix (when m=3) to which it adds an extra element. So that now distance is a cell array with 3 vectors of sizes 108021, 108022 and 108022...

Anyone knows whats wrong here?

Thanks!

Auesro

1
Don't you want something like distance{m}(i) = norm(.... Now the vector distance is overwritten with each outer loop iteration, and since the middle loop makes the vector 108022 elements, it will keep this last element untouched in the last iteration, i.e. when m=3. - rinkert
Thanks for that! That was actually the problem. However, I cannot directly make ``distance´´ a cell array because I apply ```movmean´´´ to each distance vector and it requires a numeric input... - Augusto Escalante

1 Answers

0
votes

You could preallocate the distance variable to a matrix and store the values there.

distance = zeros(length(data),max(cellfun('size',data,1)));
for m = 1:length(data)
 for i = 1:length(data{m})
  distance(m,i) = norm(data{m}(i,13:14)-data{m}(i,15:16));
 end
end

or if distance had to be a cell array

for m = 1:length(data)
 for i = 1:length(data{m})
  d{m}(i) = norm(data{m}(i,13:14)-data{m}(i,15:16));
 end
end