Cody https://www.mathworks.com/matlabcentral/cody/ 是MATLAB官方刷题网站,我从2023年6月开始每天做一道题,尽量用最简洁的方法
Problem 37. Pascal's Triangle
Pascal's Triangle - MATLAB Cody - MATLAB Central
Given an integer n >= 0, generate the length n+1 row vector representing the n-th row of Pascal's Triangle.
Examples:
pascalTri(0)
ans =
1
pascalTri(1)
ans =
1 1
pascalTri(2)
ans =
1 2 1
function y = pascalTri(n)
y=abs(pascal(n+1,1));
y=y(end,:);
end
Problem 38. Return a list sorted by number of occurrencesReturn a list sorted by number of occurrences - MATLAB Cody - MATLAB Central
Given a vector x, return a vector y of the unique values in x sorted by the number of occurrences in x. Ties are resolved by a sort from lowest to highest.
So if x = [1 2 2 2 3 3 7 7 93]
then y = [2 3 7 1 93]
function y = popularity(x)
u = unique(x);
[~,b] = sort(sum(x'==u),'descend');
y = u(b);
end
Problem 39. Which values occur exactly three times? 比Problem 38更简单,同样的方法
function y = threeTimes(x)
u = unique(x);
y = u(sum(x'==u) == 3);
end
Problem 40. Reverse Run-Length EncoderReverse Run-Length Encoder - MATLAB Cody - MATLAB Central
Given a "counting sequence" vector x, construct the original sequence y.
A counting sequence is formed by "counting" the entries in a given sequence. This is sometimes called run-length encoding.
For example, the sequence
x = 2, 5, 1, 2, 4, 1, 1, 3
can be read as
Two 5's, one 2, four 1's, one 3
which translates to
y = 5, 5, 2, 1, 1, 1, 1, 3
So y is the reconstructed vector that corresponds to the counting sequence x.
For this problem, all elements in the sequences x and y will be in the range from 1 to 9.
function y = RevCountSeq(x)
y = repelem(x(2:2:end),x(1:2:end));
end
Problem 51. Find the two most distant points
Find the two most distant points - MATLAB Cody - MATLAB Central
Given a collection of points, return the indices of the rows that contain the two points most distant from one another. The input vector p has two columns corresponding to the x and y coordinates of each point. Return ix, the (sorted) pair of indices pointing to the remotest rows. There will always be one unique such pair of points.
So if p = [0 0;1 0;2 2;0 1]
Then ix = [1 3]
That is, the two points p(1,:) and p(3,:) are farthest apart.
function ix = mostDistant(p)
distance_matrix = squareform(pdist(p));
[row, col] = find(distance_matrix == max(pdist(p)));
ix = [col(1),row(1)];
end
但是cody不支持使用pdist,只好用笨办法
function ix = mostDistant(p)
max_distance = 0;
for i = 1:size(p,1)
for j = i+1:size(p,1)
distance = sqrt(sum((p(i,:) - p(j,:)).^2));
if distance > max_distance
max_distance = distance;
ix = [i,j];
end
end
end
end