2015-03-19 40 views
0

我想寫一個函數變換(A),當給定矩陣A返回一個新的矩陣。如果A有多於一行然後交換第一行和第二行,則應根據以下內容獲得新矩陣: 。在此之後,第一行中的元素正方形。 到目前爲止,這就是我寫了:Matlab - 難以獲得我的功能輸出

function[Anew] = transform(A) 
dimension = size(A); 
if dimension(1) > 1   %if there is more than 1 row 
    A([1 2],:)=A([2 1],:); 
end 
A(1,:,:) = A(1,:,:).^2   %squares elements in the first row 
end 

我用MATLAB調用它測試我的功能。 我注意到,因爲我沒有A旁邊的分號(1,:,:) = A(1,:,:)。我仍然獲得所需的結果,但不是函數的輸出。我得到了A = 而不是Anew =

如果我在A(1,:,:) = A(1,:,)。那麼我根本沒有得到輸出。

你能告訴我什麼是錯的,我應該在我的程序中更改以獲取A new輸出? 謝謝

回答

0

要從Matlab函數中返回一個值,必須直接賦值給它。 在你的情況下,你需要在操作結束時分配給Anew(你也可以在技術上只需使用那個變量全部在一起)。

function [Output1, Output2] = SomeFunction(...) 
    % Do Some Work 

    % Store Output 
    Output1 = Result1(:,2) %some output 
    Output2 = Result2(3:end, :) %some other result 
end 

function[Anew] = transform(A) 
    dimension = size(A); 
    Anew = A; 
    if dimension(1) > 1   %if there is more than 1 row 
     Anew ([1 2],:)=Anew([2 1],:); 
    end 
    Anew(1,:,:) = Anew(1,:,:).^2;   %squares elements in the first row 
end 
+0

我在最後結束前添加了Anew = A。它的工作還沒有返回重新= = ....它返回ans = ....最新錯誤? @Rollen D'Souza – Hannah 2015-03-19 01:26:02

+0

這就是功能的工作原理。變量名稱只是函數內的一種佔位符。當你使用這個函數時,你仍然需要把它分配給某些東西(否則它保留在'ans'變量中) – 2015-03-19 01:27:24

+0

,因爲我需要用命令A([1 2],:))交換行1和2(A [2 1],:)由於這一步由賦值組成,所以我不知道我可以如何介入Anew – Hannah 2015-03-19 01:27:43