【Cody】Basics on Vectors

链接地址

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值