How do I use a struct as a function input?
이전 댓글 표시
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
Stephen23
2017년 4월 13일
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.
채택된 답변
추가 답변 (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.
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!