Matlab编程处理矩阵

Matlab programming dealing with matrix

我正在尝试其中一个 matlab 编程问题。

问题:

Write a function called hulk that takes a row vector v as an input and returns a matrix H whose first column consist of the elements of v, whose second column consists of the squares of the elements of v, and whose third column consists of the cubes of the elements v. For example, if you call the function likes this, A = hulk(1:3) , then A will be [ 1 1 1; 2 4 8; 3 9 27 ].

我的代码:

function H = hulk(v)
H = [v; v.^2; v.^3];
size(H) = (n,3);
end

当我使用 A = hulk(1:3) 测试我的代码时,它在控制台上抛出错误。

Your function made an error for argument(s) 0

我做错了什么吗?我错过了什么吗?

删除行size(H) = (n,3); 并添加行 H = H';

最终代码应该如下

function H = hulk(v)
    H = [v; v.^2; v.^3];
    H = H';
end

您的代码在 matlab 编辑器中的 size(H) = (n,3); 行给出错误

这就是为什么您应该使用 matlab编辑器本身

为了您将来的参考,您可以非常轻松地在 Matlab 中推广此函数,以允许用户指定输出矩阵中的列数。我还建议您通过确保即使您的用户提交行向量也使用列向量来使此函数更具防御性。

function H = hulk(v, n)

    %//Set default value for n to be 3 so it performs like your current function does when called with the same signature (i.e. only 1 argument)
    if nargin < 2 %// nargin stands for "Number of ARGuments IN"
        n = 3;
    end if

    %// Next force v to be a row vector using this trick (:)
    %// Lastly use the very useful bsxfun function to perform the power calcs
    H = bsxfun(@power, v(:), 1:n);

end

您可以使用 cumprod 减少操作次数。这样,每个 v.^k 计算为前 v.^kv:

function H = hulk(v, n)
H = cumprod(repmat(v,n,1),1);

第一个输入参数是向量,第二个是最大指数。