Creating new vectors containing values based on for loop outcome.

조회 수: 1 (최근 30일)
Michael Abram
Michael Abram 2020년 12월 31일
편집: dpb 2021년 1월 2일
I would like to create a new vector which contains values from b which correspond to the closest values from a. I mainly code in python and am new to Matlab. The only thing i can think of at the moment is an if statement which i know would most likely be inefficient. Essentially i would need to create new vectors for each value in a. The following is my code. Any help is greatly appreciated, thanks in advance.
a=[1250 2320 3520 7650];
b= [3700 6766 8888 1212 2000 5555 9998 3000];
vals=zeros(7,1);
n=1;
for i = b
differences = abs(a-i);
[minDiff, indexOfMinDiff] = min(differences);
closestValue = a(indexOfMinDiff);
vals(n)= closestValue;
n=n+1;
end
edges = unique(vals)
counts = histc(vals(:), edges)

채택된 답변

dpb
dpb 2020년 12월 31일
편집: dpb 2020년 12월 31일
vals=interp1(a,a,b,'nearest','extrap');
For above a,b:
>> vals
vals =
3520.00 7650.00 7650.00 1250.00 7650.00 7650.00 3520.00
>>
  댓글 수: 10
Michael Abram
Michael Abram 2021년 1월 1일
편집: dpb 2021년 1월 2일
I apologise, my description of what i wanted was extremely basic and i have finally managed to create the correct code. I apologise if i have wasted your time and am extremely thankful to you for taking the time to help me. The code to check the nearest value you gave me was extremely helpful. As you can see, the cent1 array contains the mean values of all the X values which share the same closest value in Incent1. I am aware of the kmeans function however i believe the problem i have been set involves creating my own kmeans function.
filename = 'Centroids.txt';
[inCent,delimiterOut]=importdata(filename);
filename = 'EPdata.txt';
[X,delimiterOut]=importdata(filename);
X1 = X.';
inCent1 = inCent.';
vals=interp1(inCent1,inCent1,X1,'nearest',"extrap");
n=1;
cent1=[];
for i = inCent1
k = find(vals==i);
l=length(k);
y=X(k);
s=sum(y)/l;
cent1(n)=s;
n=n+1;
end
cent1
dpb
dpb 2021년 1월 2일
편집: dpb 2021년 1월 2일
filename = 'Centroids.txt';
[inCent,delimiterOut]=importdata(filename);
filename = 'EPdata.txt';
[X,delimiterOut]=importdata(filename);
vals=interp1(inCent,inCent,X,'nearest',"extrap");
n=0;
cent=zeros(numel(inCent),1);
for i = inCent.'
n=n+1;
cent(n)=mean(X(vals==i));
end
removing duplicated variables; only transposing where needed and eliminate unnecessary temporaries and the explicit find for the logical addressing vector.
Alernatively, can eliminate the explicit loop with
filename = 'Centroids.txt';
[inCent,delimiterOut]=importdata(filename);
filename = 'EPdata.txt';
[X,delimiterOut]=importdata(filename);
vals=interp1(inCent,inCent,X,'nearest',"extrap");
cent=arrayfun(@(i) mean(X(X==vals)),vals);
NB: air code, untested....

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Debugging and Analysis에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by