How to have presistent physical constants?

Hello,
I know Matlab can do pi. I would also like to add values for other constants such as electron charge, Boltzman constant, etc. and simply have them accessible as ec and kb. However, I don't want them to get wiped out when I do a "clear all" command, so simply defining them in startup.m isn't what I want. Basically, I want them to be treated just like how Matlab treats pi (i.e. they still exist even after I clear all variables). Is there a simple way to do this?
Thanks

 採用された回答

James Tursa
James Tursa 2017 年 1 月 26 日
編集済み: James Tursa 2017 年 1 月 26 日

1 投票

If you want to do it the way pi is done, then create your own function files. E.g.,
% File ec.m on the path
function result = ec
result = 1.6021766208e-19;
end
and separately,
% File kb.m on the path
function result = kb
result = 5.670367e-8;
end
However, as Walter mentions, it might be better to package all of your constants up into a single variable (e.g., struct) that can be imported via a single function.

2 件のコメント

beanbag
beanbag 2017 年 1 月 31 日
Thanks. I only had a few constants, so I resorted to doing this. But if I need more constants, is there a more compact way to bundle them all together, without having to reference them in a "something.const" format? i.e. keep the variable name super short, like ec and kb.
Thanks
Walter Roberson
Walter Roberson 2017 年 1 月 31 日
Create functions for them. You could put all of the functions into one directory and put the directory onto your MATLAB path.

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2017 年 1 月 26 日

0 投票

pi is a function. It even takes arguments.
Some people prefer to use a Package to store constants and import from the package

3 件のコメント

per isakson
per isakson 2017 年 1 月 26 日
編集済み: per isakson 2017 年 1 月 26 日
"It even takes arguments." &nbsp Not R2016a - afaik
>> pi(3)
Error using pi
Too many input arguments.
Walter Roberson
Walter Roberson 2017 年 1 月 26 日
I thought I had once used pi('single') . Perhaps I misremembered.
Steven Lord
Steven Lord 2017 年 1 月 31 日
I don't think pi has ever accepted an input argument. You may be thinking of Inf, NaN, ones, zeros, etc. which do allow you to specify just a class name to obtain an appropriate scalar. Different functions accept different class names. For example if you try to call NaN('int32') it will error but ones('int32') will work fine.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeVariables についてさらに検索

製品

タグ

質問済み:

2017 年 1 月 26 日

コメント済み:

2017 年 1 月 31 日

Community Treasure Hunt

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

Start Hunting!

Translated by