Porblem with indexing using a loop

1 view (last 30 days)
Iliqe
Iliqe on 28 Jan 2021
Commented: Iliqe on 28 Jan 2021
The idea is to find indices of K smallest values from every column of matrix "lag", but when you run the code you will see that the resulted matrix "indices" gives only "0" and only one column gives result.
Could anyone help to handle this problem.
clear;
% import the data which should be a vector of (X, Y, Z, Value)
data=xlsread('raw5x5example.csv');
% Insert the coordinate properties of target blocks
x0= 0; y0=0;z0=0;% origin
nx = 5; ny = 5; nz = 1; % number of blocks along X, Y, and Z
dx = 1; dy= 1; dz= 1; % dimension of blocks along X, Y, and Z
block = [x0 + kron(ones(ny*nz,1),dx*[0:nx-1]'), y0 + kron(kron(ones(nz,1),dy*[0:ny-1]'),ones(nx,1)), z0 + kron(dz*[0:nz-1]',ones(nx*ny,1))];
% initialize the array of lags
lag = ones(size(block,1),size(block,1));
% calculation of lags between all points
for i=1:size(block,1)
d=ones(size(data,1),1)*block(i,1:3)-data(:,1:3);
lag(:,i)=ones(size(data,1),1).*sqrt(d(:,1).^2+d(:,2).^2+d(:,3).^2);
end
% number of points to consider in kNN
k = 6;
% initialize the variable "smallest_N_values_lag"
smallest_N_values_lag = zeros(k,size(block,1));
for i=1:size(block,1)
% get the k-smallest numbers from the i-th column of array lag
smallest_N_values_lag(:,i) = mink(lag(:,i), k);
% initialize the array of indices
indices = zeros(k, size(block,1));
% initialize counter
count = 1;
% loop over all the num-smallest numbers
for j = 1:k
% check for multi-occurrence of a component
if j > 1
if smallest_N_values_lag(j, i) == smallest_N_values_lag(j - 1, i)
count = count + 1;
else
count = 1;
end
end
% find the indices of the component in the i-th column of array Lag
idx = find(lag == smallest_N_values_lag(j, i));
% place the found index in the array of indices appropriately
indices(j, i) = idx(count);
end
end

Accepted Answer

Jan
Jan on 28 Jan 2021
Edited: Jan on 28 Jan 2021
You overwrite the array indices in each iteration:
% Move here <------------------------------------\
for i=1:size(block,1) % |
... % |
indices = zeros(k, size(block,1)); % --> ----/
...
for j = 1:k
...
indices(j, i) = idx(count);
end
end
Move the creation by indices=zeros() before the "for i" loop.
  1 Comment
Iliqe
Iliqe on 28 Jan 2021
thank you for your help)
Haven't noticed such an obvious mistake.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by