Saving a matrix with a variable that could take any value
44 views (last 30 days)
Show older comments
Scott Banks
on 20 Jan 2026 at 23:55
Commented: Scott Banks
on 21 Jan 2026 at 10:39
Hi guys,
I would like to save a matrix, by where there is a variable that could take on any value. This is the matrix I would like to save and call up in any script at any time:
SM = [12/L^3 6/L^2 -12/L^3 6/L^2;
4/L -6/L^2 2/L 6/L^2;
-12/L^3 -6/L^2 12/L^3 -6/L^2;
2/L -6/L^2 4/L 6/L^2]
The variable in this case is 'L'.
How can I do this?
Many thanks!
0 Comments
Accepted Answer
Torsten
on 21 Jan 2026 at 0:24
Edited: Torsten
on 21 Jan 2026 at 1:04
Either define the matrix as a function handle
SM = @(L)[12/L^3 6/L^2 -12/L^3 6/L^2;
4/L -6/L^2 2/L 6/L^2;
-12/L^3 -6/L^2 12/L^3 -6/L^2;
2/L -6/L^2 4/L 6/L^2];
SM(2)
or as a function
Lmat = matrix(2)
function Lmat = matrix(L)
Lmat = [12/L^3 6/L^2 -12/L^3 6/L^2;
4/L -6/L^2 2/L 6/L^2;
-12/L^3 -6/L^2 12/L^3 -6/L^2;
2/L -6/L^2 4/L 6/L^2];
end
If you save the function as "matrix.m" in your working directory, it can be called from any script at any time.
More Answers (1)
dpb
on 21 Jan 2026 at 0:30
The matrix is undefined unless and until L is defined -- barring symbolic variable.
The easiest solution it would appear would be to create it as an anonymous function
SM = @(L)[12/L^3 6/L^2 -12/L^3 6/L^2;
4/L -6/L^2 2/L 6/L^2;
-12/L^3 -6/L^2 12/L^3 -6/L^2;
2/L -6/L^2 4/L 6/L^2];
L=1;
M=SM(L)
You can save/load SM at will to evaluate when needed with whatever L is needed...
L=pi;
M=SM(L)
See Also
Categories
Find more on Operators and Elementary Operations 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!