삽질예방/Matlab

matlab 구조체

Kwang-sung Jun 2009. 7. 1. 19:17
구조체는 다음과 같이 쓴다. 원소를 더 추가하고 싶으면
circle(2).어쩌구.. 라고 쓰면 새로이 멤버가 추가된다.
>> circle.radius = 3.4;
>> circle.color='green';
>> circle.linestyle=':';
>> circle.center = [2.3 -1.2];
>> circle

circle =

1x1 struct array with fields:
    radius
    center
    color
    linestyle


다음과 같이 일괄적으로 구조체를 생성하는 방법도 있다.
>> values1 = {2.5 'sqrt(2)' 25.4};
>> values2 = {[0 1] [2.3 -1.2] [-1 0]};
>> values3 = {'--' ':' '-.'};
>> values4 = {'red', 'green', 'blue'};
>> values5 = {'yes', 'no', 'yes'};

circle = struct('radius', values1, 'center', values2, ...
'linestyle', values3, 'color', values4, 'filled',values5);


현재 circle구조체는 멤버가 셋이며 이 경우 다음과 같은 표현을 쓸 수 있다. 스트링을 이용하여 구조체의 멤버 접근을 일반적으로 할 수 있다는 것은 언젠가 편하게 쓰일 것 같다.

>> fldstr = 'color';
>> circle.(fldstr)

ans =
red

ans =
green

ans =
blue

fieldnames(circle) % 모든 필드 이름의 리스트를 리턴한다.