How do I use a formula out of a cellarray in a for-loop?

1 view (last 30 days)
Hi Community,
In measurement evaluation it is necassary to analyze uncertainties (e).
Time = Data(:,1);
Temperatur = Data(:,2);
In my Gui it should be possible to choose an e_i from an array:
Formula1 = 'a*Temperatur+b';
Formula2 = 'a*Temperatur+2b'; % and so on
DefaultAccuracy = {Formula1; Formular2...};
A popupmenu gives a value k that stands for the Input Accuracy:
InputAccuracy = DefaultAccuracy {1, k};
If I use e = a*Temperatur+b the errorbar order works:
errorbar(Time, Temperatur, e)
In the next step e should be variable:
MeasurementLength = lenght(Data);
How do I have to develop a for-loop to get e by choosing the formula with the popupmenu
for i = 1:MeasurementLength
e{i} = InputAccuracy{Temperatur{i}}
end
Please excuse my bad english and thanks for helping me! Christian

Accepted Answer

Guillaume
Guillaume on 3 Jul 2015
Edited: Guillaume on 4 Jul 2015
A dirty way would be to use eval.
A slightly cleaner way would be to use str2func to build an anonymous function handle.
InputAccuracy = DefaultAccuracy{k};
ErrorFunction = str2func(['@(a, Temperatur, b)' InputAccuracy]);
e = ErrorFunction(Temperatur);
The downside of this approach is that the strings in DefaultAccuracy have to be valid matlab operations, with the correct variable names.
In my opinion, the best way is to modify your DefaultAccuracy cell array to hold two columns, the first one, the function as it appears in the GUI (can be any text), the second one a function handle to the formula, in matlab syntax:
ErrorFunctions = {'a*Temperatur+b', @(a, T, b) a*T+b;
'a*Temperatur+2b', @(a, T, b) a*T+2b;
'Extra accurate', @(a, T, b) a*T+3b};
%In gui display ErrorFunctions{:, 1}, user select index k
ErrorFunction = ErrorFunctions{k, 2};
e = ErrorFunction(a, Temperatur, b)
Note: you seem to be confusing {} and () indexing. In your example, in the loop it should have been:
e(i) = ...Temperatur(i)...
And of course, you don't actually need a loop since you can apply the formula to the whole vector of temperatures at once.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!