How can I create a for loop when the range is changing
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hello,
I have a code as following. Code works as intended it sorts the elements as I want. After that I want to print the first element of sorted array and the corresponding distance. Actually each distance represents a song but I didn't write their names therefore I use the index of distance. My problem is there are some duplicates is sorted array. So, when I run the code if there are two times 0.5 distance it prints the same line 2 times. I somehow need to delete all coppies of sorted(i) without changing the lenght of it. If I just delete it since i goes until 19 sorted(i) will give error of index out of range. How can I solve this problem?
clc;clear;
Crescendo = [0 1 0 1 0 0 1 1 0 0 1 1 0 0 1 1 0 1 0 0]';
Descrescendo = [1 1 1 1 1 1 1 1 1 0 1 1 1 1 0 0 1 1 0 0]';
Staccato = [0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 1 1 0 0 0]';
Portamento = [0 0 0 1 0 1 1 1 0 0 0 1 1 0 0 1 0 1 0 0]';
Tempo = [1 1 1 0 1 0 1 0 0 1 1 1 1 0 1 0 0 0 1 1]';
Intervals = [0 1 1 1 1 1 0 1 1 0 0 0 1 0 0 1 1 1 1 1]';
M = [Crescendo Descrescendo Staccato Portamento Tempo Intervals];
S = M*M';
[U,W,V] = svds(S,2);
%labels = cellstr(num2str([1 : length(U)]'));
%plot(U(: ,1),U(: ,2),'rx');
%text(U(: ,1),U(: ,2), labels)
distance = zeros(19,1);
for i=2:20
distance(i-1,1) = dot(U(1,:),U(i,:))/(norm(U(1,:))*norm(U(i,:)));
end
sorted = sort(distance,"descend");
for i=1:19
index = find(distance==sorted(i));
[m,n] = size(index);
if m == 3
fprintf("Song number %d, %d and %d are %f close to song 1\n",index,sorted(i))
elseif m == 2
fprintf("Song number %d and %d are %f close to song 1\n",index,sorted(i))
else
fprintf("Song number %d is %f close to song 1\n",index,sorted(i))
end
end
0 Kommentare
Antworten (1)
Matt J
am 24 Dez. 2022
Crescendo = [0 1 0 1 0 0 1 1 0 0 1 1 0 0 1 1 0 1 0 0]';
Descrescendo = [1 1 1 1 1 1 1 1 1 0 1 1 1 1 0 0 1 1 0 0]';
Staccato = [0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 1 1 0 0 0]';
Portamento = [0 0 0 1 0 1 1 1 0 0 0 1 1 0 0 1 0 1 0 0]';
Tempo = [1 1 1 0 1 0 1 0 0 1 1 1 1 0 1 0 0 0 1 1]';
Intervals = [0 1 1 1 1 1 0 1 1 0 0 0 1 0 0 1 1 1 1 1]';
M = [Crescendo Descrescendo Staccato Portamento Tempo Intervals];
S = M*M';
[U,W,V] = svds(S,2);
U=normalize(U,2,'n');
distance = U(2:19,:)*U(1,:).';
sorted=flip(unique(distance));
for i=1:numel(sorted)
index = find(distance==sorted(i));
m=numel(index);
if m == 3
fprintf("Song number %d, %d and %d are %f close to song 1\n",index,sorted(i))
elseif m == 2
fprintf("Song number %d and %d are %f close to song 1\n",index,sorted(i))
else
fprintf("Song number %d is %f close to song 1\n",index,sorted(i))
end
end
0 Kommentare
Siehe auch
Kategorien
Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!