>> A = [ 8 1 6 ; 3 5 7 ; 4 9 2]
A =
8 1 6
3 5 7
4 9 2
>> A(2,3)
ans =
7
>> size(A)
ans =
3 3
clc %clear command window
clear %workspace의 모든 변수를 지움
exit %matlab 종료
>> clear
>> A = magic(3) %크기가 3x3인 마방진정방행렬 생성
A =
8 1 6
3 5 7
4 9 2
>> open magic %함수내부(M-file.m)
>> A' %matrix를 transpose한다. 선형대수학에선 A^T로 정의
ans =
8 3 4
1 5 9
6 7 2
>> sum(A)
ans =
15 15 15
>> sum(A,1)
ans =
15 15 15
>> sum(A')
ans =
15 15 15
>> sum(A,2)'
ans =
15 15 15
>> diag(A)
ans =
8
5
2
>> sum(diag(A))
ans =
15
>> fliplr(A) %행렬의 좌우를 변경 cf) flipud 행렬의 위아래를 변경
ans =
6 1 8
7 5 3
2 9 4
>> sum(diag(fliplr(A)))
ans =
15
>> ones(4)
ans =
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
>> zeros(5,4)
ans =
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
>> rand(2,3)
ans =
0.8147 0.1270 0.6324
0.9058 0.9134 0.0975
>> eye(4)
ans =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
function M = magic(n)
%MAGIC Magic square.
% MAGIC(N) is an N-by-N matrix constructed from the integers
% 1 through N^2 with equal row, column, and diagonal sums.
% Produces valid magic squares for all N > 0 except N = 2.
% Copyright 1984-2002 The MathWorks, Inc.
% $Revision: 5.15 $ $Date: 2002/04/15 03:44:23 $
% Historically, MATLAB's magic was a built-in function.
% This M-file uses a new algorithm to generate the same matrices.
n = floor(real(double(n(1)))); %입력변수 n의 소수점, 허수 무시
% Odd order. n이 홀수일 때
if mod(n,2) == 1
[J,I] = meshgrid(1:n); %range 1~n
A = mod(I+J-(n+3)/2,n);
B = mod(I+2*J-2,n);
M = n*A + B + 1;
% Doubly even order. n이 4의 배수일 때
elseif mod(n,4) == 0
[J,I] = meshgrid(1:n);
K = fix(mod(I,4)/2) == fix(mod(J,4)/2);
M = reshape(1:n*n,n,n)';
M(K) = n*n+1 - M(K);
% Singly even order. n이 4의 배수가 아닌 짝수 일 때
else
p = n/2;
M = magic(p); %재귀함수
M = [M M+2*p^2; M+3*p^2 M+p^2];
if n == 2, return, end
i = (1:p)';
k = (n-2)/4;
j = [1:k (n-k+2):n];
M([i; i+p],j) = M([i+p; i],j);
i = k+1;
j = [1 i];
M([i; i+p],j) = M([i+p; i],j);
end
'Matlab' 카테고리의 다른 글
Control Flow (0) | 2013.12.23 |
---|---|
M-file (0) | 2013.12.23 |
Matrix Operator (0) | 2013.12.23 |
MATLAB 기호프로세서(symbolic processor) 기초2 (0) | 2013.09.02 |
MATLAB 기호프로세서(symbolic processor) 기초 (0) | 2013.09.02 |