Matlab - 难以获得我的函数的输出

Matlab - difficulty getting output for my function

我正在尝试编写一个函数 transform(A),当给定一个矩阵 A returns 时,它是一个新矩阵。新矩阵应根据以下内容获得: 如果 A 有多行,则交换第一行和第二行。在此之后平方第一行中的元素。 到目前为止,这就是我写的内容:

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,:,:).^2
旁边没有分号 我仍然获得了想要的结果,但不是函数的输出。 我得到 A = 而不是 Anew =

如果我在 A(1,:,:) = A(1,:,:).^2 旁边放一个分号;然后我根本没有得到输出。

你能告诉我哪里出了问题吗?我应该在我的程序中更改什么以重新获得输出? 谢谢

要return 来自 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