How to change the value of a vector through sub functions
Mostra commenti meno recenti
Hello-
pretend:
prisoner = 1:2
outcomes = []
bias = .25
choice = zeros(1,2)
These are sub functions and I want to only change 1 element of the 'choice' vector eachtime the main function is called. How could this be done?
These are only a part of the subfunctions, but this is where I'm struggling..
%prisoner cooperate (1)
function [choice(1)] = prisoner_coop(prisoner,outcomes,bias)
choice(1) = 1
end
%prisoner defect (2)
function [choice(2)] = prisoner_defect(prisoner,outcomes,bias)
choice(2) = 0
end
8 Commenti
Brian Peoples
il 17 Mar 2019
Walter Roberson
il 17 Mar 2019
Which one element of choice should be changed?
When you say they are sub functions, do you mean that you have nested functions in which choice is a variable in the main function, so choice could act like a shared variable?
Brian Peoples
il 17 Mar 2019
Walter Roberson
il 17 Mar 2019
function your_main_function(appropriate,parameters,go,here)
num_choice = 16;
choice = nan(1, num_choice);
prisoners = randi(5,1,10);
outcomes = [];
bias = 0.25;
prisoner_coop(prisoners, outcomes, bias);
prisoner_defect(prisoners, outcomes, bias);
function prisoner_coop(prisoner, outcomes, bias)
choice(1) = 1;
end
function prisoner_defect(prisoner, outcomes, bias)
choice(2) = 0;
end
end
Brian Peoples
il 17 Mar 2019
Modificato: Brian Peoples
il 17 Mar 2019
Walter Roberson
il 17 Mar 2019
Your main function can have whatever parameter you need . But you have to initialize them somewhere .
Matlab does not offer "subfunctions". It offers functions. Only the first function in a file can normally be invoked directly from outside the .m (except for static class methods) but you can have any number of function declarations in one .m
It is possible in some circumstances to declare a function inside of another function . Such functions are known as nested functions and can make use of shared variables .
I think you are saying that you are not using nested functions inside your main function . If that is the case you cannot use shared variables with it.
There are ways to change a unshared variable in a function from a function that it calls directly . That is not recommended . The recommended approach is nested functions with shared variables , or simply making the variable both an input and an output .
Walter Roberson
il 17 Mar 2019
What does your project have to do with transfer functions or embedded matlab functions ? You tagged a number of things that look irrelevant at the moment .
Risposte (0)
Categorie
Scopri di più su Solver Outputs and Iterative Display in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!