链接地址
https://ww2.mathworks.cn/matlabcentral/cody/groups/172
Problem 3. Find the sum of all the numbers of the input vector
Problem 6. Select every other element of a vector
Problem 247. Arrange Vector in descending order
If x=[0,3,4,2,1] then y=[4,3,2,1,0]
function y = desSort(x)
r = length(x)
p = 0
for i = 1:r
for j = 1:r
if x(i) > x(j)
p = x(i)
x(i) = x(j)
x(j) = p
else
continue
end
end
end
y = x
end
Problem 135. Inner product of two vectors
Find the inner product of two vectors.
function y = your_fcn_name(x,y)
y = dot(x,y);
end
Problem 624. Get the length of a given vector
Given a vector x, the output y should equal the length of x.
function y = VectorLength(x)
y = length(x);
end
Problem 1107. Find max
Find the maximum value of a given vector or matrix.
function y = your_fcn_name(x)
[r,c] = size(x)
y = x(1,1)
for i = 1:r
for j = 1:c
y = max( x(i,j), y )
end
end
end
Problem 605. Whether the input is vector?
Given the input x, return 1 if x is vector or else 0.
function y = checkvector(x)
[r,c] = size(x)
if (r == 1 & c >= 1) | (c == 1 & r >= 1)
y = 1
else
y = 0
end
end
Problem 1065. Make a 1 hot vector
Make a vector of length N that consists of all zeros except at index
k, where it has the value 1.Example:
Input
N = 6; k = 2; vector = one_hot(N,k);
Output
vector = [0 1 0 0 0 0]
function vector = one_hot(N,k)
tem = zeros(1,N);
tem(1,k) = 1
vector = tem
end
Problem 2631. Flip the vector from right to left
Flip the vector from right to left.
Examples
x=[1:5],
then y=[5 4 3 2 1]x=[1 4 6],
then y=[6 4 1];Request not to use direct function.
function y = flip_vector(x)
r = length(x)
for i = 1:r
y(r+1-i) = x(i)
end
end
Problem 3076. Create a vector
Create a vector from 0 to n by intervals of 2.
function y = zeroToNby2(n)
y = 0:2:n;
end
Problem 1024. Doubling elements in a vector
Given the vector A, return B in which all numbers in A are doubling.
So for:A = [ 1 5 8 ]
then
B = [ 1 1 5 5 8 8 ]
function B = your_fcn_name(A)
r = 2*length(A)
p = 1
for i = 1:2:r
B(i) = A(p)
B(i+1) = A(p)
p = p+1
end
end
Problem 42651. Vector creation
Create a vector using square brackets going from 1 to the given value
x in steps on 1.Hint: use increment.
function y = vector(x)
y = 1:1:x;
end