第一题 Problem 3. Find the sum of all the numbers of the input vector
Find the sum of all the numbers of the input vector x.
Examples:
Input x = [1 2 3 5]
Output y is 11
Input x = [42 -1]
Output y is 41
输出给定向量的和。
function ans = vecsum(x)
sum(x)
end
第二题 Problem 6. Select every other element of a vector
Write a function which returns every other element of the vector passed in. That is, it returns the all odd-numbered elements, starting with the first.
Examples:
Input x = [1 3 2 4 3 5]
Output y is [1 2 3]
Input x = [5 9 3 2 2 0 -1]
Output y is [5 3 2 -1]
返回输入向量下标为奇数的值组成的向量。
function y = everyOther(x)
y = x(1:2:end);
end
第三题 Problem 247. Arrange Vector in descending order
If x=[0,3,4,2,1] then y=[4,3,2,1,0]
对数组进行从大到小排列,可以类似c++使用sort进行排序:
第一种由于sort是从小到大排序,对排序后的结果翻转即可。第二种是用sort(x,'descend')进行从大到小排序。
function y = desSort(x)
y = flipdim(sort(x),2);
end
或y=sort(x,'descend')
第四题 Problem 135. Inner product of two vectors
Find the inner product of two vectors.
返回两个向量的内积,对两个向量进行点乘后求和即可。
function z = your_fcn_name(x,y)
z = sum(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.
输出向量x的大小y,使用length函数。
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)
y = max(max(x));
end
或y=max(x(:))
第七题 Problem 605. Whether the input is vector?
Given the input x, return 1 if x is vector or else 0.
判断输入的x是否是向量,可以直接使用函数isvector,或用size()得到x的行数和列数后判断是否至少有一个为1.
function y = checkvector(x)
y = isvector(x);
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.
对向量进行翻转。测试用例都是行向量,所以使用flipdim(y,2),即按列翻转;如果是列向量,那么第二个参数改为1,为按行。
function y = flip_vector(x)
y=flipdim(x,2);
end
第九题 Problem 3076. Create a vector
Create a vector from 0 to n by intervals of 2.
返回一个从0到n并且间隔为2的向量。直接用0:2:n即可。
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 ]
将A的元素进行double,比如A=[a b c c d] 那么B=[a a b b c c c c d d],即长度扩大一倍,连续出现x次的元素double后连续出现2x次,x可以为1。在这里先创建一个二倍长的向量B,令其所有偶数索引等于A,所有奇数索引也等于A。(参考第二题)
function B = your_fcn_name(A)
B=zeros(1,2*length(A));
B(1:2:end)=A;
B(2:2:end)=A;
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.
创建一个步长为1 并且1到x的向量,使用方括号(square brackets)
提示:使用增量
其实我没太看懂题意 直接1:x了,评论区也没有人说这事
function y = vector(x)
y = 1:x;
end