[MATLAB 기초 문법] 4. 데이터 구조 & 문자열

YUN·2026년 2월 16일

MATLAB/Simulink

목록 보기
7/21
post-thumbnail

1. 셀 배열 (Cell Array)

일반 행렬은 같은 타입, 같은 크기만 저장 가능하나, 셀 배열은 아무거나 다 담을 수 있는 만능 배열이다.

(1) 셀 배열 생성

중괄호({})로 셀 배열을 생성할 수 있다.

% ── 중괄호 { }로 생성 ──
C = {1, 'hello', [1 2 3], true};

% ── 각 칸에 다른 타입/크기 가능! ──
%   C{1} = 1           (double)
%   C{2} = 'hello'     (char)
%   C{3} = [1 2 3]     (1×3 벡터)
%   C{4} = true        (logical)

% ── 빈 셀 배열 ──
D = cell(2, 3);    % 2×3 빈 셀 배열 (각 칸이 [])

% ── 2차원 셀 배열 ──
table = {'이름',  '나이', '학과';
         '민지',   24,    '전자공학';
         '민수',   23,    '컴공'};

(2) 셀 배열 접근 : { } vs ( )

셀 배열의 특정 인덱스에 접근 하는 방법은 총 2 가지로, {} 또는 () 를 사용한다.

  • {} : 내용물만 반환
  • () : 셀 자체를 반환 (즉, 내용물을 cell로 감싼 채로 반환)
C = {10, 'hello', [1 2 3]};

% ── { } → 내용물 꺼내기 (content) ──
C{1}            % 10            ← double 숫자
C{2}            % 'hello'       ← char 배열
C{3}            % [1 2 3]       ← 벡터
C{3}(2)         % 2             ← 벡터의 2번째 원소

% ── ( ) → 셀 자체 (cell로 감싼 채로) ──
C(1)            % {10}          ← 1×1 cell
C(1:2)          % {10, 'hello'} ← 1×2 cell (부분 셀 배열)

(3) 셀 배열 수정 & 추가

셀 내용 수정 및 추가는 {}를 사용하고 셀 삭제는 () 를 사용하낟.

C = {'a', 'b', 'c'};

% ── 내용 수정 ──
C{2} = 99;             % {'a', 99, 'c'}

% ── 추가 (인덱스 확장) ──
C{5} = 'new';          % {'a', 99, 'c', [], 'new'}
                       %  4번째는 자동으로 빈 칸

% ── 삭제 ──
C(3) = [];             % 3번째 칸 삭제 (소괄호!)

⚠️ 삭제할 때는 소괄호 ( ) 와 빈 배열 [] 을 사용한다.

C{3} = []은 삭제가 아니라 내용을 빈 배열로 바꾸는 것이라 삭제와 다르다.

(4) 셀 배열 활용 예시

% ── 여러 학생 데이터 저장 ──
students = {'지현', 95, [90 85 100];
            '민수', 82, [78 88 80];
            '수진', 91, [95 87 91]};

students{1,1}           % '지현'
students{2,2}           % 82
students{3,3}           % [95 87 91]
mean(students{3,3})     % 91  (수진의 평균 점수)

% ── 셀 배열 순회 ──
names = {'지현', '민수', '수진'};
for i = 1:length(names)
    fprintf('학생: %s\n', names{i});
end

(5) 셀 관련 함수

C = {1, 'hi', [1 2]};

iscell(C)           % true       — 셀인지 확인
length(C)           % 3          — 길이
size(C)             % [1, 3]     — 크기

% ── 셀 ↔ 일반 변환 ──
nums = {1, 2, 3, 4};
mat = cell2mat(nums)    % [1 2 3 4]   셀 → 행렬 (타입 통일 시만)

mat = [10 20 30];
C = num2cell(mat)       % {10, 20, 30}  행렬 → 셀

% ── cellfun: 각 셀에 함수 적용 ──
words = {'hello', 'hi', 'matlab'};
lengths = cellfun(@length, words)    % [5 2 6]  각 문자열 길이

2. 구조체 (Struct)

C의 구조체와 비슷하다. 이름(필드)로 데이터를 정리한다.

(1) 구조체 생성

구조체명.필드명 = 데이터로 구조체에 필드를 추가할 수 있다.

% ── 방법 1: 점(.) 표기법으로 필드 추가 ──
student.name = '도윤';
student.age = 25;
student.scores = [90 85 92];
student.dept = '전자공학부';

% ── 방법 2: struct() 함수로 한 번에 ──
student = struct('name', '도윤', ...
                 'age', 25, ...
                 'scores', [90 85 92], ...
                 'dept', '전자공학부');

(2) 필드 접근, 수정

구조체.필드명 으로 특정 필드에 접근 및 수정이 가능하다.

student.name            % '재윤'
student.scores          % [90 85 92]
mean(student.scores)    % 89

% 수정
student.age = 26;

% 필드 추가 (그냥 쓰면 됨)
student.gpa = 4.4;

(3) 동적 필드 접근

구조체명.(변수명) 으로 변수에 담긴 필드명에 접근할 수 있다.

field = 'name';
student.(field)         % '재윤'   ← 점 + 소괄호!

% 활용: 여러 필드를 루프로 처리
fields = {'name', 'age', 'dept'};
for i = 1:length(fields)
    fprintf('%s: ', fields{i});
    disp(student.(fields{i}));
end

(4) 구조체 배열

구조체명(배열인덱스).필드명 = 데이터 로 구조체 배열을 생성한다.

% ── 여러 학생을 배열로 ──
students(1).name = '재윤';
students(1).age = 25;
students(1).score = 95;

students(2).name = '민수';
students(2).age = 23;
students(2).score = 82;

students(3).name = '수진';
students(3).age = 24;
students(3).score = 91;

% 접근
students(2).name        % '민수'
students(3).score       % 91

% 전체 점수 뽑기
all_scores = [students.score]    % [95 82 91]  ← 자동 연결!
mean(all_scores)                 % 89.3333

[구조체명.필드명] : 구조체의 해당 필드를 전부 꺼내서 벡터로 반환한다.

(5) 구조체 관련 함수

s = struct('x', 1, 'y', 2, 'z', 3);

fieldnames(s)           % {'x'; 'y'; 'z'}  — 필드 이름 목록
isfield(s, 'x')        % true              — 필드 존재 여부
rmfield(s, 'z')        % z 필드 제거한 새 구조체 반환

isstruct(s)            % true              — 구조체인지 확인

% 구조체 → 셀
values = struct2cell(s)  % {1; 2; 3}

3. 문자열

MATLAB에서 문자열은 문자 배열(char)과 문자열(string) 총 2 가지 종류가 존재한다.

(1) 문자 배열(char 배열) VS 문자열(string)

  • 문자 배열 : 작은 따옴표(') 로 나타낸다
  • 문자열 : 큰 따옴표(') 로 나타낸다.
% ── 문자 배열: 작은따옴표 ' ' ──
c = 'Hello';
class(c)        % 'char'
length(c)       % 5         ← 글자 하나하나가 원소
c(1)            % 'H'       ← 인덱싱 가능 (배열이니까)
c(2:4)          % 'ell'

% ── 문자열: 큰따옴표 " " (R2016b+) ──
s = "Hello";
class(s)        % 'string'
strlength(s)    % 5         ← length 대신 strlength
% s(1)          % "Hello"   ← 인덱싱이 글자 단위가 아님!

(2) 문자열 연결

문자 배열 스타일은 배열과 동일하게 연결한다. 반면 문자열(string)은 +로 연결한다.

% ── char 방식 ──
a = 'Hello';
b = ' World';
c = [a b]                  % 'Hello World'  (배열 연결)
c = strcat(a, b)           % 'Hello World'

% ── string 방식 ──
s1 = "Hello";
s2 = "World";
s3 = s1 + " " + s2        % "Hello World"  (+ 연산자!)

% ── sprintf (서식 지정) ──
name = '도윤';
age = 25;
msg = sprintf('%s님은 %d세입니다.', name, age);
% '도윤님은 25세입니다.'

(3) 문자열 변환

% ── 숫자 ↔ 문자 ──
num2str(42)             % '42'
num2str(3.14, '%.2f')   % '3.14'      (서식 지정)
str2double('3.14')      % 3.14
str2num('42')           % 42

% ── char ↔ string ──
string('hello')         % "hello"     char → string
char("hello")           % 'hello'     string → char

% ── 숫자를 문자열에 삽입 ──
x = 42;
msg = ['결과: ' num2str(x) '점'];    % char 방식
msg = "결과: " + x + "점";           % string 방식 (숫자->string 자동 변환!)

(4) 문자열 비교

% ⚠️ == 로 비교하면 글자 단위 비교! (길이 다르면 에러 발생시킴)
'abc' == 'abc'          % [1 1 1]  (logical 배열)
% 'abc' == 'ab'         % ❌ 에러! 길이 다름

% ── 올바른 비교 ──
strcmp('hello', 'hello')     % true    정확히 같은지
strcmp('Hello', 'hello')     % false   정확히 같은지 구분하므로 대소문자도 구분한다
strcmpi('Hello', 'hello')   % true    대소문자 차이 무시

% ── string은 == 가능 ──
"hello" == "hello"           % true (logical 스칼라)

(5) 문자열 검색, 분석

str = 'MATLAB is great for engineers';

% ── 포함 여부 ──
contains(str, 'great')        % true
contains(str, 'Great')        % false (대소문자 구분)
contains(str, 'Great', 'IgnoreCase', true)  % true

% ── 시작/끝 확인 ──
startsWith(str, 'MAT')       % true
endsWith(str, 'ers')         % true

% ── 위치 찾기 ──
strfind(str, 'great')        % 11    (시작 인덱스)
strfind(str, 'a')            % [2 8 13]   (여러 위치)

(6) 문자열 조작

% ── 대소문자 변환 ──
upper('hello')              % 'HELLO'
lower('HELLO')              % 'hello'

% ── 공백 제거 ──
strtrim('  hello  ')        % 'hello'    (앞뒤 공백)

% ── 치환 ──
strrep('I like C++', 'C++', 'MATLAB')
% 'I like MATLAB'

replace("I like C++", "C++", "MATLAB")    % string 방식

% ── 분할 ──
parts = strsplit('one,two,three', ',')
% {'one', 'two', 'three'}   ← 셀 배열!

parts = split("one,two,three", ",")
% ["one"; "two"; "three"]   ← string 배열

% ── 결합 ──
strjoin({'one', 'two', 'three'}, '-')
% 'one-two-three'

join(["one", "two", "three"], "-")
% "one-two-three"

(7) 서식 지정 출력 (fprintf/sprintf)

% ── fprintf: 화면에 출력 ──
fprintf('정수: %d\n', 42);            % 정수: 42
fprintf('실수: %.3f\n', 3.14159);     % 실수: 3.142
fprintf('문자열: %s\n', 'hello');     % 문자열: hello
fprintf('퍼센트: %.1f%%\n', 95.5);    % 퍼센트: 95.5%

% ── sprintf: 문자열로 저장 ──
msg = sprintf('점수: %d / %d', 85, 100);
% '점수: 85 / 100'
profile
안녕하세요. 전자공학부 학부생의 공부 기록입니다.

0개의 댓글