How do I create a three-column matrix that consists of the elements, squares, and cubes of a row vector?
Show older comments
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
Sara Gallant
on 11 May 2015
Accepted Answer
More Answers (1)
>> 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
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!