lec 03. matlab data types
TRANSCRIPT
MATLAB Programming
MATLAB Data Types
2
MATLAB Programming
Numeric Data Types
default numeric data type은 double
• 데이터 타입 확인은 >> class(A)• 데이터 타입 별 min/max 값은 정수의 경우 intmin() / intmax(), 실수의 경우
realmin() / realmax()
Data Type Size (bytes) Min Maxint8 1 -128 128
int16 2 -32768 32767
int32 4 -2147483648 2147483647
uint8 1 0 255
uint16 2 0 65535
uint32 4 0 4294967295
single 4 1.1755e-38 3.4028e+38
double 8 2.2251e-308 1.7977e+308
3
MATLAB Programming
Numeric Data Type간 변환
변환하고자 하는 데이터 타입의 이름을 함수처럼 사용하여, 행렬을 매개변수로주면 됨
주의할 점• 데이터 범위가 더 넓은 데이터 타입에서 데이터 범위가 좁은 데이터 타입으로 변환 시,
데이터 손실이 있을 수 있음.• eg) A = uint32(257)와 B = int8(A)는 서로 다른 값
>> A = rand(5,3);
>> sA = single(A)
>> ui8 = uint8(A)
>> ui16 = uint16(sA)
>> double(ui16)
>> …
4
MATLAB Programming
Numeric Data Type 변환 하는 이유?
1. 매우 큰 배열을 만들 때, 메모리를 절약하기 위해
2. 크기가 큰 여러 배열들 간의 연산 시, 계산 속도를 빨리 하기 위해
>> clear all; clc;
% double 타입의 1000 x 1000 행렬생성>> dA = rand(1000,1000);>> class(dA)ans =
double
% double 타입행렬을 single 타입으로변환>> sA = single(dA);>> class(sA)ans =
single
% 두배열이차지하는메모리공간확인
>> whosName Size Bytes Class Attributes
dA 1000x1000 8000000 double sA 1000x1000 4000000 single
5
MATLAB Programming
문자열
문자열은 작은 따옴표로 나타냄
두 문자열의 합성
• 문자열은 1 x n 배열로 취급됨
• 따라서 두 문자열의 합성은 두 1 x n 배열의 합성 방법과 동일
• 대부분의 경우 두 문자열의 길이가 서로 다르므로, [x; y] 와 같이 문자열을 합성하려고
하면 에러가 남
>> x = ‘hello world’x =
hello world
>> x = ‘hello ’>> y = ‘world’>> z = [x y]z =hello world
6
MATLAB Programming
문자열
문자열의 길이
문자열 배열 생성 방법 I
• 각 문자의 길이가 동일하도록 spacebar로 맞춰준다.
>> length(z)ans =
11
>> A = [‘apple’; ‘orange’]Error using vertcatDimensions of matrices being concatenated are not consistent.
>> A = ['apple '; 'orange']A =apple orange
7
MATLAB Programming
문자열
문자열 배열 생성 방법 II
문자열 배열에서 각 문자열 접근 방법
>> a = 'apple';>> b = 'orange';>> c = 'bananas';>> abc = char(a,b,c)
abc =
apple orange bananas
>> abc( 1, : )ans =
apple
>> abc( 2, : )ans =
orange
>> abc( 3, : )ans =
bananas
8
MATLAB Programming
Cell 데이터 타입
숫자 10과 문자 ‘Hello World’를 동시에 한 배열에 저장할 수 있을까?
Cell array는 서로 다른 타입의 데이터들을 한 곳에 저장 가능
>> [10 'Hello World']ans =
Hello World
실패!!의도와전혀다른예상치못한결과
>> A{1,1} = 10A =
[10]
>> A{1,2} = 'hello world'A =
[10] 'hello world'
올바른결과
9
MATLAB Programming
Cell 데이터 타입
Cell() 함수 이용하여 Cell 데이터 생성
Cell 데이터 시각화• 각 셀에 어떠한 타입의 데이터가 있는지 보여줌
>> A = cell(1,2)A =
[] []
>> A{1,1} = 10
A = [10] []
>> A{1,2} = 'hello world'
A = [10] 'hello world'
1 x 2 크기의 cell 배열생성
• 배열원소접근방법과동일• []이아니라 {}임을주의
>> cellplot(A, ‘legend’)
10
MATLAB Programming
Cell 데이터 타입
Cell 안에 Cell 넣기
Cell 안에 Cell의 원소 접근하기
>> C = { [1 2], ‘hello’ ; ‘world’, [3, 4] }
C = [1x2 double] 'hello' 'world' [1x2 double]
>> D = {C, 'kaist'; 'academy', 2014}
D = {2x2 cell} 'kaist''academy' [2014]
>> cellplot(D, ‘legend’)
% “hello” 원소에접근하기
>> D{1,1}{1,2}
% [1 2] 배열의원소접근하기
>> D{1,1}{1,1}(1)
11
MATLAB Programming
Cell에 문자열 저장하기
>> C = cell(1,3)
C = [] [] []
>> C{1} = 'Seoul'
C = 'Seoul' [] []
>> C{2} = 'Daejeon'
C = 'Seoul' 'Daejeon' []
>> C{3} = 'Busan'
C = 'Seoul' 'Daejeon' 'Busan‘
>> cellplot(C)
문자열저장하기 문자열가져오기
>> >> C{1}
ans =Seoul
>> C{2}
ans =Daejeon
>> C{3}
ans =Busan
12
MATLAB Programming
Quiz
문제 7) 다음과 같은 원소들로 구성된 2 x 2 Cell 배열을 만들어 봅시다.
[1 2] ′KA𝐼𝐼𝐼𝐼𝐼𝐼′2 + 3𝑖𝑖 5
13
MATLAB Programming
struct (구조체) 데이터 타입
예) 학사 데이터• 성명: 홍길동• 학번: 20010132• 학점: 3.9
서로 연관 있는 데이터들을 하나의 묶음으로 관리할 수 있도록 하는데이터 타입• 성명, 학번, 학점 등의 데이터는 서로 연관성이 있으므로, 이를 묶어서관리하는 것이 편리함
Cell과 비슷하게 서로 다른 타입의 데이터들을 저장 가능
Cell과 다르게 각 데이터들은 인덱스가 아니라 이름으로 접근• 성명, 학번, 학점 등
C/C++의 struct와 동일한 개념
C{1,1} = ‘홍길동’C{2,1} = 20010132C{3,1} = 3.9
Cell로관리하는것이편리할까?
14
MATLAB Programming
struct 데이터 타입
struct 데이터 생성
struct의 각 field 접근
>> s = struct('name', '홍길동', 'id', 20010132, 'gpa', 3.9)
s = name: '홍길동'id: 20010132
gpa: 3.9000
>> s.name
ans =
홍길동
>> s.id
ans =
20010132
>> s.gpa
ans =
3.9000
>> s = struct;>> s.name = '홍길동';>> s.id = 20010132;>> s.gpa = 3.9;>> s
s =
name: '홍길동'id: 20010132
gpa: 3.9000
또는
빈구조체정의
각필드정의
15
MATLAB Programming
struct 데이터 타입
struct의 각 field 값 변경
기존 struct에 새로운 field 추가
>> s.name = '홍길도'
s = name: '홍길도'id: 20010132
gpa: 3.9000
>> s.id = 140001
s = name: '홍길도'id: 140001
gpa: 3.9000
>> s.gpa = 4.3
s = name: '홍길도'id: 140001
gpa: 4.3000
>> s.major = 'Computer Science'
s = name: '홍길도'
id: 140001gpa: 4.3000
major: 'Computer Science' 새로추가된필드
16
MATLAB Programming
struct 데이터 생성
다양한 타입의 데이터로 구성 가능
>> a = struct;>> a.city = '서울';>> a.temperature = [0 -3 -5 -7 -1 0 1];>> a.wind = {'북서풍', '약함'}
a =
city: '서울'temperature: [0 -3 -5 -7 -1 0 1]
wind: {'북서풍' '약함'}
>> a.info = struct('pressure', [1013.2 1013.5],'time', [9 10 11]);
>> a
a =
city: '서울'temperatures: [0 -3 -5 -7 2 1]
wind: {'북서풍' '약함'}info: [1x1 struct]
>> a.info
ans = pressure: [1.0132e+03 1.0135e+03]
time: [9 10 11]
구조체내에구조체저장
17
MATLAB Programming
구조체 배열 (struct array)
동일한 구조체들의 나열
구조체 배열 생성 및 각 배열 원소에 접근
>> a = struct;>> a.city = '서울';>> a.temperature = [0 -3 -5 -7 -1 0 1];>> a.wind = {'북서풍', '약함'};
a = city: '서울'
temperature: [0 -3 -5 -7 -1 0 1]wind: {'북서풍' '약함'}
>> weather(10) = a
weather =
1x10 struct array with fields:
citytemperaturewind
>> weather(10)ans =
city: '서울'temperature: [0 -3 -5 -7 -1 0 1]
wind: {'북서풍' '약함'}
>> weather(3)ans =
city: []temperature: []
wind: []
>> weather(10).city
ans =서울
>> weather(10).temperature(4)
ans =-7
18
MATLAB Programming
구조체 배열
구조체 배열 생성 방법 II• 어느 한 필드라도 그 값이 cell array로 정의되면, 모든 필드의 값들도 똑같은
size의 cell array가 된다.
>> weather = struct(‘city’, {‘서울’, ‘대전’, ‘부산‘}, …‘temp’, {-5, 1, 3}, …‘time’, 13)
weather =
1x3 struct array with fields:
citytemptime
>> weather(1)
ans = city: '서울'temp: -5time: 13
>> weather(2)
ans = city: '대전'temp: 1time: 13
>> weather(3)
ans = city: '부산'temp: 3time: 13
19
MATLAB Programming
구조체 배열
구조체 배열 생성 방법 II• 어느 한 필드라도 그 값이 cell array로 정의되면, 모든 필드의 값들도 똑같은 size의 cell
array가 된다.
• cell의 각각 원소가 하나씩 뽑혀져 구조체를 생성하고, 그 구조체가 순서대로 모여구조체 배열을 이룸
>> weather = struct(‘city’, {‘서울’, ‘대전’, ‘부산‘}, …‘temp’, {-5, 1, 3}, …‘time’, 13)
weather =
1x3 struct array with fields:
citytemptime
>> weather(1)
ans = city: '서울'temp: -5time: 13
>> weather(2)
ans = city: '대전'temp: 1time: 13
>> weather(3)
ans = city: '부산'temp: 3time: 13 20
MATLAB Programming
구조체 배열
구조체 배열 생성 방법 II
• 서로 다른 필드에서 cell size가 동일하지 않으면?
>> weather = struct(‘city’, {‘서울’, ‘대전’, ‘부산‘}, …‘temp’, {-5, 1}, …‘time’, 13)
Error using structArray dimensions of input '4' must match those of input '2', or be scalar.
1 x 3 cell array
1 x 2 cell array
21
MATLAB Programming
구조체 배열
빈 구조체 배열 생성 방법 III
• 한 field에 빈 cell을 생성하면, 해당 cell 크기와 동일한 크기의 구조체 배열생성
>> weather = struct('city', cell(1,5), 'temp', [], 'time', [])
weather =
1x5 struct array with fields:
citytemptime
>> weather(1)
ans =
city: []temp: []time: []
1 x 5 cell array
22
MATLAB Programming
struct 데이터 생성시 주의할 점
두 결과가 왜 다른가?
>> a = struct;>> a.city = '서울';>> a.temperature = [0 -3 -5 -7 -1 0 1];>> a.wind = {'북서풍', '약함'}
a =
city: '서울'temperature: [0 -3 -5 -7 -1 0 1]
wind: {'북서풍' '약함'}
>> a = struct('city', '서울', 'temperatures',[0 -3 -5 -7 2 1], 'wind', {'북서풍', '약함'})
a =
1x2 struct array with fields:
citytemperatureswind
>> a(1)
ans =
city: '서울'temperatures: [0 -3 -5 -7 2 1]
wind: '북서풍'
>> a(2)
ans =
city: '서울'temperatures: [0 -3 -5 -7 2 1]
wind: '약함'
≠
23
MATLAB Programming
struct 데이터 생성시 주의할 점
두 결과를 같게 만드려면?• cell array를 제외한 필드를 먼저 생성하고, cell array를 위한 필드를 추가
>> a = struct;>> a.city = '서울';>> a.temperature = [0 -3 -5 -7 -1 0 1];>> a.wind = {'북서풍', '약함'}
a =
city: '서울'temperature: [0 -3 -5 -7 -1 0 1]
wind: {'북서풍' '약함'}
>> a = struct('city', '서울', 'temperatures',[0 -3 -5 -7 2 1]);
>> a.wind = {'북서풍', '약함'}
a =
city: '서울'temperatures: [0 -3 -5 -7 2 1]
wind: {'북서풍' '약함'}
≡
24
MATLAB Programming
Quiz
아래와 같이 학적에 관한 구조체를 생성해봅시다.
student
student(1)
.name
“김철수”
.id
20130142
.gpa
.semester
봄학기
.score
[3.4 3.5 3.9 4.1]
student(2)
.name
“이민수”
.id
20130562
.gpa
.semester
봄학기
.score
[3.5 3.1 3.9 3.6]
25
MATLAB Programming
Quiz Sol.
아래와 같이 학적에 관한 구조체를 생성해봅시다.student
student(1)
.name
“김철수”
.id
20130142
.gpa
.semester
봄학기
.score
[3.4 3.5 3.9 4.1]
student(2)
.name
“이민수”
.id
20130562
.gpa
.semester
봄학기
.score
[3.5 3.1 3.9 3.6]
>> students = struct('name', {'김철수', '이민수'}, 'id', {20130142, 20130562}, 'gpa', struct())
>> students(1).gpa.semester = '봄학기‘
>> students(1).gpa.score = [3.4 3.5 3.9 4.1]
>> students(2).gpa.semester = '봄학기‘
>> students(2).gpa.score = [3.5 3.1 3.9 3.6]26
MATLAB Programming
여러 필드에 동시에 접근하기
앞의 Quiz에서 생성한 students 구조체 배열에서, 모든 학생들의 이름을 얻어오고 싶을 때
• 방법 I. students 배열의 길이만큼 변수를 적어준다.
• 방법 II. 동일한 길이의 좌변 (LHS) 배열에 할당해준다.
>> [n1, n2] = students.name
n1 =김철수
n2 =이민수
>> z = cell( length(students), 1 )>> [z{:}] = students.name
>> z(1)
ans = '김철수'
>> z(2)
ans = '이민수' 27
MATLAB Programming
구조체 필드 삭제, 이름 얻어오기
필드 삭제 : rmfield
구조체의 필드 이름 얻어오기
>> students = rmfield(students, 'gpa')
students =
1x2 struct array with fields:
nameid
>> fieldnames(students)
ans =
'name''id'
28
MATLAB Programming
구조체 필드 정렬
orderfields 함수
• 구조체 배열의 field를 정렬
• snew = orderfields( sold )
구조체/구조체 배열 sold의 field를 사전 순서대로 정렬
• snew = orderfields( sold , c )
구조체/구조체 배열을 cell c에 적힌 fieldname 순으로
정렬
• snew = orderfields( sold , perm )
구조체/구조체 배열을 perm 순서대로 정렬
• [snew , perm] = orderfields( … )
field를 각 정렬 방법에 따라 정렬하고, 정렬된 구조체
snew와 필드의 정렬 순서를 함께 리턴
>> sold = struct('b', 2, 'c', 3, 'a', 1)
sold = b: 2c: 3a: 1
>> snew = orderfields(sold)
snew = a: 1b: 2c: 3
>> snew = orderfields(sold, {'a', 'c', 'b'})
snew = a: 1c: 3b: 2
>> snew = orderfields(sold, [3 2 1])
snew = a: 1c: 3b: 2
>> [snew, perm] = orderfields(sold)
snew = a: 1b: 2c: 3
perm =312 29
MATLAB Programming
구조체의 is* 함수
isfield
• 구조체의 field가 맞으면 true, 아니면 false 리턴
• TF = isfield( s, fieldname )
isstruct
• 구조체가 맞으면 true, 아니면 false 리턴
• TF = isstruct( s )
>> s = struct('one',1,'two',2)
s = one: 1two: 2
>> fields = isfield(s,{'two','pi','One',3.14})
fields =1 0 0 0
>> isstruct(struct('name', 1))
ans =1
>> isstruct({1, 2, 'hi'})
ans =0
30
MATLAB Programming
cell 데이터를 struct 데이터로 변환
cell2struct
• S = cell2struct( C, FIELDS, DIM )
• cell 배열 C를 구조체 S로 변환
• FIELDS 는 구조체 S로 변환되었을 때 field 이름
• size(C, dim) 은 FIELDS 에 기술된 field 이름의 개수와 동일해야 함
>> c = {'tree',37.4,'birch'}
c =
'tree' [37.4000] 'birch'
>> f = {'category','height','name'}
f =
'category' 'height' 'name'
>> s = cell2struct(c,f,2)
s =
category: 'tree'height: 37.4000
name: 'birch'
31
MATLAB Programming
cell 데이터를 struct 배열 데이터로 변환
cell2struct
• S = cell2struct( C, FIELDS, DIM )
>> c = {'jisung park' 185 'korea'; 'bumgun cha', 182, 'korea'}
c = 'jisung park' [185] 'korea''bumgun cha' [182] 'korea'
>> f = {'name' 'height' 'nationality'}
f = 'name' 'height' 'nationality'
>> s = cell2struct(c, f, 2)
s =
2x1 struct array with fields:
nameheightnationality
>> s(1)
ans =
name: 'jisung park'height: 185
nationality: 'korea'
>> s(2)
ans =
name: 'bumgun cha'height: 182
nationality: 'korea'
32
MATLAB Programming
struct 데이터를 cell 데이터로 변환
struct2cell
• C = struct2cell( S )
• P개의 field를 가진 M x N 구조체 배열을 P x M x N cell 배열로 변환
• 구조체 배열이 1차원인 경우, P x size(S) cell 배열로 변환
>> s2 = struct;>> s2.cateogry = 'tree';>> s2.height = 37.4;>> s2.name = 'birch';>> s2
s2 =
cateogry: 'tree'height: 37.4000name: 'birch'
>> c = struct2cell(s2)
c = 'tree' [37.4000]'birch'
>> f = fieldnames(s2)
f = 'cateogry''height''name'
33
MATLAB Programming
struct 배열을 cell 배열로 변환
struct2cell
• C = struct2cell( S )
>> struct2cell(s)
ans =
'jisung park' 'bumgun cha'[ 185] [ 182]'korea' 'korea'
>> f = fieldnames(s)
f =
'name''height''nationality'
34
MATLAB Programming
struct 배열을 cell 배열로 변환
struct2cell
• C = struct2cell( S )
• 3개의 field를 가진 2 x 2 구조체 배열을 3 x 2 x 2 cell 배열로
변환하는 예
>> sr = repmat(s, 1, 2)
sr =
2x2 struct array with fields:
nameheightnationality
>> c = struct2cell(sr)
c(:,:,1) =
'jisung park' 'bumgun cha'[ 185] [ 182]'korea' 'korea'
c(:,:,2) =
'jisung park' 'bumgun cha'[ 185] [ 182]'korea' 'korea'
35