10. vector indexing
• v=1:2:10
• v(5)
• v(1:3)
• v(:)
• v(end)
• v(1:end~=3)
• Try it:
• Get the 2nd element
from v.
• Get 3rd to end
elements.
• Put 1st, 3rd, 5th
element as a new
array named b.
11. matrix indexing
• matrix
• m=[1:3;4:6;7:9]
1 2 3
4 5 6
7 8 9
• matrix
• m=[1:3;4:6;7:9]
• m(1,:) % get 1st row
• m(:) % get all
element
• m(1:2,3) % submatrix
• m(8) ???
• linear indexing
• m([1,4,5,6])
12. try it
• m = magic(5)
• Get first column from m.
• Get 3~5 rows from m.
• Get submatrix which formed by the intersection of 1~3
rows and 2~4 columns of m and store in a new matrix
m1(3x3 matrix).
• Get a column vector which formed by all the odd linear
index elements in m.
25. if…else
• grade = 65;
• if grade >= 60
• disp('Pass~');
• else
• disp('Fail!! QQ~');
• end
26. for loop
• grades = [60,50,40,70];
• names = {'John','Peter','Chen','Lucky'};
• for i=1:numel(grades)
• if grades(i) >= 60
• disp([names(i) ': Pass']);
• else
• disp([names(i) ': Fail']);
• end
• end
27. try it
• m = magic(100);
• Get row index and column index (i,j) for all the
elements which grater than 3.
28. some tips for speed up
•
• zeros(n,m)
• for loop
• tic;toc; %timer
• JIT compiler
•
• logical array find
29. N = 1e7;
tic
w = zeros(1, N);
for i = 1:N
w(i) = i*5;
end
fprintf('For loop: %.4fsn', toc);%=> 0.053s
tic
y = (1:N)*5;
fprintf('Vectorized: %.4fsn', toc);%=> 0.082s
Try it:
feature(‘accel’,’off’);
and run again
30. parfor
N = 1e7;
tic
w = zeros(1, N);
parfor i = 1:N
w(i) = i*5;
end
fprintf('Parfor loop: %.4fsn', toc);
%=> 1.853s
31. homework
• matlab
• id =
• id_last = id
• y=5sin(2/id_last*x) 2
• x 0 10pi 500
•
• AM2 MATLAB <id>
• x 0 10pi pi
• 20
• ceiba