Saving a matrix with a variable that could take any value

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!

 採用された回答

Torsten
Torsten 2026 年 1 月 21 日
編集済み: Torsten 2026 年 1 月 21 日

1 投票

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)
ans = 4×4
1.5000 1.5000 -1.5000 1.5000 2.0000 -1.5000 1.0000 1.5000 -1.5000 -1.5000 1.5000 -1.5000 1.0000 -1.5000 2.0000 1.5000
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
or as a function
Lmat = matrix(2)
Lmat = 4×4
1.5000 1.5000 -1.5000 1.5000 2.0000 -1.5000 1.0000 1.5000 -1.5000 -1.5000 1.5000 -1.5000 1.0000 -1.5000 2.0000 1.5000
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
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.

その他の回答 (1 件)

dpb
dpb 2026 年 1 月 21 日

1 投票

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)
M = 4×4
12 6 -12 6 4 -6 2 6 -12 -6 12 -6 2 -6 4 6
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
You can save/load SM at will to evaluate when needed with whatever L is needed...
L=pi;
M=SM(L)
M = 4×4
0.3870 0.6079 -0.3870 0.6079 1.2732 -0.6079 0.6366 0.6079 -0.3870 -0.6079 0.3870 -0.6079 0.6366 -0.6079 1.2732 0.6079
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

カテゴリ

ヘルプ センター および File ExchangeOperators and Elementary Operations についてさらに検索

質問済み:

2026 年 1 月 20 日

コメント済み:

2026 年 1 月 21 日

Community Treasure Hunt

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

Start Hunting!

Translated by