How do I use a struct as a function input?
Mostra commenti meno recenti
I have a function that accepts up to 4 strings(they are 'rule1Before, rule1After, etc.' below) and in the the function these strings are set to struct values. In stead of hard coding these rules I would like to have one input, perhaps rules and then proceed as below. Any suggestions on how to handle this scenario? Thanks in advance!
function axiomGrowth = LsysExpand(rule1Before,rule1After,rule2Before,rule2After)
% LsysExpand: Expands from starting seed based on given parameters
% Inputs:
% numberOfIterations: number of times rules are applied
% axiom: the initial point from which growth occurs
% rule1Before: intital condition for rule 1
% rule1After: if rule1Before exists apply rule1After
% ...
% substituion rules
rule(1).before = rule1Before;
rule(1).after = rule1After;
% The arguments below are optional.
if nargin > 4
rule(2).before = rule2Before;
rule(2).after = rule2After;
end
1 Commento
Stephen23
il 13 Apr 2017
Note to others: Do not use the accepted answer: it is buggy and very inefficient. See my answer for a much simpler, neater, and more efficient solution.
Risposta accettata
Più risposte (1)
Assuming that rules is a cell array of strings, then you just need this:
>> rules = {'bef1','aft1','bef2','aft2','bef3','aft3'};
>> rulesParsed = struct('before',rules(1:2:end),'after',rules(2:2:end))
That is all. Now lets test it:
>> rulesParsed(2).before
ans =
bef2
>> rulesParsed(2).after
ans =
aft2
Perfect. It produces the same structure as the OP's self-accepted answer, containing the same data. Just simpler, faster, and neater.
Categorie
Scopri di più su Loops and Conditional Statements 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!