2017-04-26 171 views
0

我想這樣的:如果如何使矩陣的對角線等於另一個矩陣的對角線?

a=1 2 3 
4 5 6 
7 8 9 i want a at the end to be 

            a= 1 6 9 
            12 25 18 
            49 24 81 

這意味着對角線我做到了以方也相對對角線 和其他在我multpplied他們的3個矩陣elemnts ..所以我 有這個至今:

a=rand(n) 
c=fliplr(diag(diag(a)).^2)+(tril(a,-1)+triu(a,1)*3) 
i=(diag(diag(fliplr(a)))).^2 
c(1:n+1:n^2)=0 
result=fliplr(c+i) 

這個作品,如果我在一個COMAND窗口做到這一點,但我想它寫爲 功能!提前致謝。

+0

你格式化是有點瘋狂,考慮[編輯]荷蘭國際集團後正確 –

回答

0

較短和計算速度更快的替代使用邏輯索引是使用元素方式乘法和元素方面的權力。

% function b = myfun(a) 
n = 10000 
a = randi(10,n); 
I = eye(size(a,1),'logical'); 
b = a.^2.*I + a.*3.*~I; 
% end 
1

它更容易使用邏輯索引。如果你想使用它作爲一個功能只需打開一個新的文件,function A = myfunc(A)

% random matrix 
n = 5; 
A = randi(10,n); 
% here you can do: 
% function A = myfunc(A) 

% diagonal indexes 
diagIdxs1 = eye(size(A),'logical'); 
diagIdxs2 = fliplr(diagIdxs1); 
diagIdxs = diagIdxs1 | diagIdxs2; 
% do operations on diagonals and on non-diagonals 
A(diagIdxs) = A(diagIdxs).^2; 
A(~diagIdxs) = A(~diagIdxs).*3; 
+0

如果我把我在一個函數寫它不會bacause工作線c(1:N + 1:N^2 )= 0,這是我的問題! – lia