简体   繁体   中英

Matlab programming dealing with matrix

I am trying out one of the matlab programming question.

Question:

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 ].

My Code:

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

When I test my code using A = hulk(1:3) , it throws an error on console.

Your function made an error for argument(s) 0

Am I doing something incorrect? Have I missed anything?

Remove the line size(H) = (n,3); and add the line H = H';

Final code should be as follows

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

Your code giving error in matlab editor on the size(H) = (n,3); line在此处输入图片说明

That's why you should use the matlab editor itself

For your future reference, you can very easily generalise this function in Matlab to allow the user to specify the number of cols in your output matrix. I also recommend that you make this function a bit more defensive by ensuring that you are working with column vectors even if your user submits a row vector.

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

You could reduce the number of operations using cumprod . That way, each v.^k is computed as the previous v.^k times v :

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

The first input argument is the vector, and the second is the maximum exponent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM