How to call a value from a file within an equation?

1 回表示 (過去 30 日間)
Nesha Wright
Nesha Wright 2018 年 7 月 20 日
コメント済み: dpb 2018 年 7 月 20 日
I have the equation :
aggRF(n)=(-1.3e-6.*(('CH4(n)'-'CH4(0'))/2)-8.2e-6*n+.043)*(sqrt(CH4(n)-sqrt(CH4(0))))
How do I call certain values from the file (attached). CH4 is the species, the number is the year. I can type CH4(#) in and it gives me the correct value but how do I do this in an equation?

採用された回答

dpb
dpb 2018 年 7 月 20 日
編集済み: dpb 2018 年 7 月 20 日
Define anonymous function--
fnAggRF=@(n)(-1.3e-6.*(('CH4(n)'-'CH4(0'))/2)-8.2e-6*n+.043)*(sqrt(CH4(n)-sqrt(CH4(0))));
Then, simply
n=23; % example 'n' vaue
AggRF=fnAggRF(n); % evaluate for n
NB: You will have to have read the .mat file and have CH4 in memory when the function handle is created to build in the constants for CH4(0); if you have more than one file or CH4 array the function must be recreated with that new/updated array in memory at the time; otherwise the function will still reflect the original values; they are not dynamically updated if the variables upon which the anonymous function is dependent are changed. See the documentation for anonymous functions for more detail.
To avoid the above, you could always make the argument list to include the array...
fnAggRF=@(CH4,n)(-1.3e-6.*(('CH4(n)'-'CH4(0'))/2)-8.2e-6*n+.043)*(sqrt(CH4(n)-sqrt(CH4(0))));
By including CH4 in the argument list, it becomes a locally-scoped dummy argument in the expression and is not the same variable as that existing in the workspace or function space.
ERRATUM:
Matlab arrays are one-based; CH4(0) must be CH4(1), sorry...
fnAggRF=@(n)(-1.3e-6.*(('CH4(n)'-'CH4(1'))/2)-8.2e-6*n+.043)*(sqrt(CH4(n)-sqrt(CH4(1))));
  7 件のコメント
Nesha Wright
Nesha Wright 2018 年 7 月 20 日
On it! THANK YOU!!!!
dpb
dpb 2018 年 7 月 20 日
As an expansion of the above idea but with a little more structure than just a "plain" 2D array with everything identified only by row and column numbers, one could build a structure with fields containing the material and coefficients and manipulate it; then one has both the commonality of the one data structure but also has way to refer to elements either by name or variables.
Similar to that also could be the table which is essentially an ordered and named 2D array that can also be operated on globally.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeFunction Creation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by