精華區beta MATLAB 關於我們 聯絡資訊
※ 引述《CDavid (UNFAIR)》之銘言: : 假設有一個矩陣M : 1 2 3 4 5 : 2 3 4 5 6 : M=3 4 5 6 7 : 4 5 6 7 8 : 5 6 7 8 9 : 原本的寫法是 : a=zeros(2,4*4) : k=1; : for i=1:4 : for j=1:4 : a(:,k)=sum(M(i:(i+1),j:(j+1))')'; : k=k+1; : end : end : 意思是把矩陣取出2*2的矩陣 : 然後把兩行相加 : 存到a矩陣 : 做出來結果會是 : 取出小矩陣 : 1 2 、 2 3 、 3 4 、 4 5 : 2 3 3 4 4 5 5 6 .....再換下一列取小矩陣 : 兩行相加 成為 : 3 、 5 、 7 、 9 : 5 7 9 11 : 存到a矩陣 : a=3 5 7 9 : 5 7 9 11........ : 這樣的2*16矩陣 : 請問有不用迴圈的方法嗎? : 謝謝 M1=reshape(repmat(M(:)',2,1),size(M,1)*2,size(M,2))'; M2=reshape(repmat(M1(:)',2,1),size(M1,1)*2,size(M1,2)); M2([1 end],:)=[]; M2(:,[1 end])=[]; a=reshape(sum(reshape(M2(:,[1:2:end,2:2:end]),[],2),2),2,[]) 基本的技巧是把重複的部份先使用repmat擴張處理 然後reshape成全部小矩陣疊在一起的樣子 最後再使用sum完成相加後 重新reshape成輸出的樣子即可 -- Deserves death! I daresay he does. Many that live deserve death. And some die that deserve life. Can you give that to them? Then be not too eager to deal out death in the name of justice, fearing for your own safty. Even the wise cannot see all ends. Gandalf to Frodo -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.120.25.235