how to make a function that takes vector as input and generate matrix of its elements
23 次查看(过去 30 天)
显示 更早的评论
Hi everyone. I am going to make a function that take a vector as input and generate a matrix such that first column of matrix show vector elements, second colmn show square of the elements of vector and third column show cube of vector and so on..... Take a look on the example here
a=1:5;
m(a)=
1 1 1 1 1
2 4 8 16 32
3 9 27 81 243
4 16 64 256 1024
5 25 125 625 3125
i am trying these codes but i unable to know how i make such matrix inside the second for loop
function H=hulk(v)
A=length(v);
H=zeros(A,A);
for i=1:A
for j=1:A
H(i,j)=i*j
end
end
end
Kindly guide me how can i correct my code or any other alternate way to solve this.Thanks in advance for assistance...
0 个评论
采纳的回答
Geoff Hayes
2015-5-9
Muhammad - a couple of things to consider. Try not to use i and j as indexing variables since both also represent the imaginary number. Note also how you are not using v as the first column of H. So first try
numElems = length(v);
H = zeros(numElems,numElems);
if ~iscolumn(v)
v = v';
end
The above assumes that v is a one-dimensional array. See how we convert v to a column vector to handle the case where it is a row vector.
Now you want each kth column of H to be v to the power of k. In your code, every element of your matrix H is just the row index multiplied by the column index which isn't what you want. Instead try
for k=1:numElems
H(:,k) = v.^k;
end
We just loop over each column of H and set it to be v to the power of k. The colon in
H(:,k)
means that we consider all rows of H (instead specifying one for example) and so we are initializing this column of H to be
v^k
Try the above and see what happens!
2 个评论
Geoff Hayes
2015-5-9
Muhammad's answer moved here
@Geoff Hayes if i want to get only the matrix which will create powers till cube.It means this will not a square matrix. take an example below
output = hulk([1 2 3 4 5])
output =
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
this will always created a matrix n*3(its 1st column is vector , second is square of elements of vector and 3rd column is cube). Where i need correction in your codes..Thanks in advance
Geoff Hayes
2015-5-9
If you only want to calculate up to the nth power, then try the following
nthPower = 3;
numElems = length(v);
H = zeros(numElems, nthPower);
if ~iscolumn(v)
v = v';
end
for k=1:nthPower
H(:,k) = v.^k;
end
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!