找到你要的答案

Q:give all integers between two numbers in MATLAB

Q:给MATLAB中的两个数之间的所有整数

Need some hints, how do i write a function called int_col that has one input argument, a positive integer n that is greater than 1, and one output argument v that is a column vector of length n containing all the positive integers smaller than or equal to n, arranged in such a way that no element of the vector equals its own index. In other words, v(k) is not equal to k for any valid index k.

i used this code

function v = int_col(n)
    v = [n:-1:1]'
end

but the solver is giving me error for input argument 3

需要一些提示,我如何写一个函数调用int_col具有一个输入参数,一个正整数n是大于1的,和一个输出参数V是一个长度为n的所有正整数小于或等于n的列向量,排列,矢量元素等于自己的指数。换句话说,V(k)是不等于K的任何有效的索引K.

我用了这个代码

function v = int_col(n)
    v = [n:-1:1]'
end

但求解器给了我输入参数3的错误

answer1: 回答1:

Her is a solution using loops:

function v = int_col(n)

v = zeros(1,n);
for index=1:n
   val = randi(n);
   while (val == index || any(val == v))
       val = randi(n);
       if (index == n && (any(v == n) ~= 1))
           val = n;
           break
       end
   end
   v(index) = val;
   if (index == n && val == n)
      v(n) = v(n-1);
      v(n-1) = n;
   end
end
v = v';
end

她是一个使用循环的解决方案:

function v = int_col(n)

v = zeros(1,n);
for index=1:n
   val = randi(n);
   while (val == index || any(val == v))
       val = randi(n);
       if (index == n && (any(v == n) ~= 1))
           val = n;
           break
       end
   end
   v(index) = val;
   if (index == n && val == n)
      v(n) = v(n-1);
      v(n-1) = n;
   end
end
v = v';
end
answer2: 回答2:
function[v]=int_col(n)
v=zeros(n,1);
k=1:n;
p=cat(2,k(n),k(1:n-1));
v=p'
end
function[v]=int_col(n)
v=zeros(n,1);
k=1:n;
p=cat(2,k(n),k(1:n-1));
v=p'
end
matlab  random  numbers  integer