矩陣搞來搞去

來源:互聯網
上載者:User

現有一矩陣a樣子如下,第一列是歌曲id,第二列是推薦的歌曲id,第三列是信賴度

想要產生一個矩陣b,每首歌要推薦5首歌曲,信賴度已經排序,所以是每首歌從上往下取出5首推薦個曲,不足5首的用0補齊,最後的樣子如下

 

1 1 0.1
1 2 0.2
1 3 0.3
1 4 0.4
1 5 0.5
1 6 0.6
1 7 0.7
1 8 0.8
1 9 0.9
2 10 1
2 11 1.1
2 12 1.2
2 13 1.3
2 14 1.4
2 15 1.5
2 16 1.6
2 17 1.7
3 18 1.8
3 19 1.9
3 20 2
3 21 2.1
4 22 2.2
4 23 2.3
5 24 2.4
5 25 2.5
5 26 2.6
5 27 2.7
5 28 2.8
5 29 2.9
5 30 3
1 1 0.1
1 2 0.2
1 3 0.3
1 4 0.4
1 5 0.5
2 10 1
2 11 1.1
2 12 1.2
2 13 1.3
2 14 1.4
3 18 1.8
3 19 1.9
3 20 2
3 21 2.1
3 0 0
4 22 2.2
4 23 2.3
4 0 0
4 0 0
4 0 0
5 24 2.4
5 25 2.5
5 26 2.6
5 27 2.7
5 28 2

 

以下是實現的代碼

b=unique(a(:,1))*ones(1,5);
b=reshape(b',numel(unique(a(:,1)))*5,1);
for i=1:length(unique(a))
x=find(b(:,1)==i);
y=find(a(:,1)==i);
if length(x)<length(y)
for j=1:length(x)
if b(x(j),1)==a(y(j),1)
b(x(j),2:3)=a(y(j),2:3);
end
end
else
for j=1:length(y)
if b(x(j),1)==a(y(j),1)
b(x(j),2:3)=a(y(j),2:3);
end
end
end
end

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.