How to I create an Array of Operations?
1 view (last 30 days)
Show older comments
Hello,
I am trying to randomly iterate optimiser variables for an image registration problem. To do this I want to randomly choose one of the optimiser variables, then change its value and measure any improvements (or lack thereof). In my case I am using these four variables:
a = randi([100,500]);
b = 1e-6 + (1e-2 - 1e-6).*rand(1);
c = rand(1);
d = 1e-5 + (1e-3 - 1e-5).*rand(1);
My idea was to create an array of the four characters, then choose one at random, and run that operation. This is what I have so far:
var_array = ['a' 'b' 'c' 'd'];
r = randi([1 4],1);
var_array_opt = var_array(r)
This would then randomly output either 'a' 'b' 'c' or 'd'. If 'c' were chosen for example, then I would want my function to perform the task assigned to variable c. I am unsure of how to do this last part, does anyone have any ideas?
0 Comments
Accepted Answer
Stephen23
on 10 Nov 2018
It is not very clear what you want, but perhaps a cell array of function handles might help:
>> C{1} = @() randi([100,500]);
>> C{2} = @() 1e-6 + (1e-2 - 1e-6).*rand(1);
>> C{3} = @() rand(1);
>> C{4} = @() 1e-5 + (1e-3 - 1e-5).*rand(1);
And then simple select using indexing and evaluate that function, e.g.:
>> C{2}()
ans = 0.0083177
>> C{4}()
ans = 0.00069951
More Answers (2)
madhan ravi
on 10 Nov 2018
Edited: madhan ravi
on 10 Nov 2018
var_array = {'a' 'b' 'c' 'd'}; %edited after sir Walter's comment
r = randi([1 4],1)
var_array_opt = var_array{r}
3 Comments
Walter Roberson
on 10 Nov 2018
Consider
var_array = ['a' 'b' 'c' 'd' 'theta'];
Using var_array(r) would retrieve a single character such as 'a', 'b', 'c', 't' rather than one variable name. If you are using single character variables then var_array = ['a' 'b' 'c' 'd']; works fine though it tends to mislead as to how it could be modified.
Now var_array = {'a' 'b' 'c' 'd'} ; and using {} indexing has no problem with multicharacter variable names.
You do not need syms for either situation. Using syms will not give you any advantage towards selecting a task according to the selected variable. The information about which task to select is already encoded into r and using syms does not change that.
Walter Roberson
on 10 Nov 2018
Tasks = {@atask,@btask,@ctask,@dtask} ;
Thistask = Tasks{r} ;
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!