I'm getting a matrix as output when I'm expecting a vector
Show older comments
I'm trying to calculate the abscisses and weight values for the Newton-Cotes method. In the end I use a linsolve() expecting to get a vector as output but instead I get a matrix. Any ideas what I could have done wrong?
a = 0;
b = 1;
n = 20;
[x,H] = NewtonCotes(a,b,n)
function [x,H] = NewtonCotes(a,b,n)
if n ~= 0
h = (b-a)/n;
else
h = (b-a);
end
for i = 1:n+1
x(i) = a + ((i-1)*h);
end
H = ComputeWeights(a,b,x);
end
function [H] = ComputeWeights(a,b,x)
n = length(x)-1;
I = ones(n+1);
I(1) = b - a;
I(2) = 0;
for i = 3:n+1
I(i) = ((b-a)*((-1)^i + 1))/(2*(1-i^2));
end
for i = 1:length(x)
x(i) = ((2/(b-a))*(x(i)-a))-1;
end
T = zeros(n+1,n+1);
for i = 1:n+1
for k = 1:n+1
T(i,k) = cos(k*acos(x(i)));
end
end
H = linsolve(T,I);
end
2 Comments
Rahul
on 6 Aug 2024
What inputs are you passing to your function?
I have tried to use some dummy inputs using your function and it was returning a vector instead of a matrix.
Torsten
on 6 Aug 2024
I is an (n+1)x(n+1) matrix in the code. So H will always be a (n+1)x(n+1) matrix, not a vector.
Answers (2)
Torsten
on 6 Aug 2024
Maybe you mean
I = ones(n+1,1);
instead of
I = ones(n+1);
Hello Arthur,
You can get a matrix as output while using linsolve to solve the linear systems of equation.
The function returns a vector or matrix that satisfies AX=B. The size of X depends on whether "opts.TRANSA" = true:
- If A is m-by-n and B is m-by-k, then X is n-by-k and is the solution to AX = B.
- If "opts.TRANSA" = true, then A is m-by-n and B is m-by-k. In this case, X is m-by-k and is the solution to A'X = B.
Here, "TRANSA" is Conjugate transpose which specifies whether the function solves A*X = B (when opts.TRANSA = false) or the transposed problem A'*X = B (when opts.TRANSA = true).
Please refer to the following documentation link for more information:
Output type for Linsolve: https://www.mathworks.com/help/matlab/ref/linsolve.html?searchHighlight=linsolve%20output%20matrix&s_tid=srchtitle_support_results_1_linsolve%20output%20matrix#mw_7666b08b-4d6b-4175-8f3b-c0c979bd9c6d.
I hope it resolves your query.
Categories
Find more on Matrices and Arrays 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!