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

3 次查看(过去 30 天)
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 个评论
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 CenterFile Exchange 中查找有关 Function Creation 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by