How do I create a three-column matrix that consists of the elements, squares, and cubes of a row vector?

Hello,
I am trying to write a function 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.
The function I've written reads like this:
function H = hulk(v)
H = [v; v.^2; v.^3];
size(H) = (n,3)
end
When I test it, I get this:
>> H = hulk(1:3)
H =
1 2 3
1 4 9
1 8 27
H =
1 2 3
1 4 9
1 8 27
>> H = hulk(1:4)
H =
1 2 3 4
1 4 9 16
1 8 27 64
H =
1 2 3 4
1 4 9 16
1 8 27 64
>> H = hulk(1:5)
H =
1 2 3 4 5
1 4 9 16 25
1 8 27 64 125
Although I should only be getting a three column vector as my output since I am just asking for squares and cubes. Any thoughts on where I am going wrong in my function?
Thank you!

1 Comment

Sorry, the function up there is wrong:
it reads as
function H = hulk(v) H = [v; v.^2; v.^3]; end

Sign in to comment.

 Accepted Answer

There are a couple ways to get the result you want, but the easiest is to simply transpose your ‘H’ matrix before you return it:
H = [v; v.^2; v.^3]';

More Answers (1)

You could play around with bsxfun:
>> v = 1:5;
>> pwr = 0:2;
>> bsxfun(@power,v(:),pwr)
ans =
1 1 1
1 2 4
1 3 9
1 4 16
1 5 25
Using bsxfun has the advantage that you can define the range of powers simply by changing the pwr vector.

Categories

Tags

Asked:

on 11 May 2015

Edited:

on 11 May 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!