67 lines
1.8 KiB
Matlab
67 lines
1.8 KiB
Matlab
clear
|
|
|
|
a1 = [1 2 3];
|
|
a2 = [4, 9, 10];
|
|
|
|
% create 3x2 matrix by joining columns
|
|
% two equivalent ways:
|
|
A = [a1.', a2.'];
|
|
A = horzcat(a1.', a2.');
|
|
A = cat(2, a1.', a2.'); % 2 selects the dimension that varies
|
|
% which is the dimension along which it concatenates
|
|
% 2 == column
|
|
|
|
% create a 2x3 matrix by joining rows
|
|
B = [a1; a2];
|
|
B = vertcat(a1, a2);
|
|
B = cat(1, a1, a2); % columns stay the same
|
|
|
|
% note:
|
|
assert(all(horzcat(a1, a2) == [1 2 3 4 9 10])); % not as above!
|
|
|
|
% also, comparision of row and column vectors gives non obvious result:
|
|
assert(all(a1 == a2.' == false(3), 'all'));
|
|
|
|
% ranges
|
|
assert(all(1:3 == [1 2 3]));
|
|
assert(all((1:3).' == [1 2 3]'));
|
|
|
|
% non integer ranges
|
|
% default step is 1
|
|
assert(all(1.5:3.5 == [1.5 2.5 3.5]));
|
|
% different step: note that 10 is included
|
|
assert(all(1 : 3 : 10 == [1 4 7 10]));
|
|
assert(all(1.3 : 2.2 : 5 == [1.3 3.5]));
|
|
|
|
C = [A [2 9 8].'];
|
|
|
|
% select one element
|
|
assert(C(2, 1) == 2);
|
|
% select element 1 and 3 on the second row
|
|
assert(all(C(2, [1 3]) == [2 9]));
|
|
% select element 1 and 3 on the first column
|
|
% note that the resulting entries are in a column vector
|
|
assert(all(C([1 3], 1) == [1 3].'));
|
|
|
|
% select the whole third row: progressively smarter
|
|
assert(all(C(3, [1, 2, 3]) == [3 10 8]));
|
|
assert(all(C(3, 1:3) == [3 10 8]));
|
|
assert(all(C(3, :) == [3 10 8]));
|
|
|
|
assert(all(C(:, :) == C, 'all'));
|
|
|
|
% select the whole second column
|
|
assert(all(C(:, 2) == [4 9 10].'));
|
|
|
|
% select the first and the third column, joining them
|
|
assert(all(C(:, [1 3]) == [1 2 3; 2 9 8].', 'all'));
|
|
|
|
|
|
% todo: linear indexing and logical indexing
|
|
% sub2ind ind2sub
|
|
assert(all(A(:) == [1 2 3 4 9 10].'));
|
|
|
|
% remove elements from an array
|
|
D = [1, 3, 6, 2, 3, 1];
|
|
D(D == 3) = []; % remove all threes
|
|
assert(isequal(D, [1, 6, 2, 1])); |