Using structures with Functions

조회 수: 5 (최근 30일)
Jeremy Mercer
Jeremy Mercer 2022년 8월 1일
댓글: Jeremy Mercer 2022년 8월 1일
I have a structure that I am using to simplify the workspace.
I have a structure called Condition defined so that I have multiple variables and each variable has an array for multiple conditions
Condition.Title(1) = {'test 1'};
Condition.Variable_a(1) = 1000
Condition.Variable_b(1) = 10
Condition.Title(2) = {'test 2'};
Condition.Variable_a(2) = 2000
Condition.Variable_b(2) = 20
such that
Condition =
Title: {'test 1' 'test 2'}
Variable_a: [1000 2000
Variable_b: [10 20]
I want to feed all the variables of a single condition into a function so I tried using this
Condition(1)
I hoped this would give me Title(1), Variable_a(1), and Variable_b(1) but it just gives me the entire stucture as if I had no index.
There are a number of variables so I don't want to enter each variable individually if I can avoid it
Is there a way to call all of the variables into a function with only a single column from the arrays?

채택된 답변

Stephen23
Stephen23 2022년 8월 1일
편집: Stephen23 2022년 8월 1일
Rather than defining a scalar structure containing arrays, it looks like you should be using a non-scalar structure:
For example:
Condition(1).Title = 'test 1';
Condition(1).Variable_a = 1000;
Condition(1).Variable_b = 10;
Condition(2).Title = 'test 2';
Condition(2).Variable_a = 2000;
Condition(2).Variable_b = 20;
Condition(1)
ans = struct with fields:
Title: 'test 1' Variable_a: 1000 Variable_b: 10
Condition(2)
ans = struct with fields:
Title: 'test 2' Variable_a: 2000 Variable_b: 20
Note that you can use comma-separated lists to obtain and assign data to the structure:
  댓글 수: 1
Jeremy Mercer
Jeremy Mercer 2022년 8월 1일
Thanks I didn't understand the difference between the two input method. This may work for me but I did have it in that form earlier and ran into issues. I'll have to reassess what that issue was and see if I can work around it as I believe a non-scaler structure will be easier to deal with.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Matt J
Matt J 2022년 8월 1일
편집: Matt J 2022년 8월 1일
@Stephen23's answer might be what you are looking for, but if you need the struct in scalar form for some reason, then the attached utility will split the fields for one-time purposes.
Condition.Title(1) = {'test 1'};
Condition.Variable_a(1) = 1000;
Condition.Variable_b(1) = 10;
Condition.Title(2) = {'test 2'};
Condition.Variable_a(2) = 2000;
Condition.Variable_b(2) = 20;
ConditionArray=arrayify_struct(Condition);
ConditionArray(1)
ans = struct with fields:
Title: {'test 1'} Variable_a: 1000 Variable_b: 10
ConditionArray(2)
ans = struct with fields:
Title: {'test 2'} Variable_a: 2000 Variable_b: 20

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by