Porblem with indexing using a loop

조회 수: 4 (최근 30일)
Iliqe
Iliqe 2021년 1월 28일
댓글: Iliqe 2021년 1월 28일
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

채택된 답변

Jan
Jan 2021년 1월 28일
편집: Jan 2021년 1월 28일
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
Iliqe
Iliqe 2021년 1월 28일
thank you for your help)
Haven't noticed such an obvious mistake.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by