首页 > 编程知识 正文

matlab函数速查手册,matlab函数调用

时间:2023-05-04 17:18:09 阅读:263039 作者:1412

最近在写matlab代码转c++,会遇到一些重写的函数。

复写首先要了解randperm函数在matlab中的实现机理。
以下是函数原定义:

function p = randperm(n);%RANDPERM Random permutation.% RANDPERM(n) is a random permutation of the integers from 1 to n.% For example, RANDPERM(6) might be [2 4 5 6 1 3].% % Note that RANDPERM calls RAND and therefore changes RAND's state.%% See also PERMUTE.% Copyright 1984-2002 The MathWorks, Inc.% $Revision: 5.10 $ $Date: 2002/04/09 00:26:14 $[ignore,p] = sort(rand(1,n));

所以代码是基于rand函数和sort函数实现的。

首先由rand函数生成随机数:

>> y=rand(1, 6)y = 0.4103 0.8936 0.0579 0.3529 0.8132 0.0099

然后sort进行排序并返回排序后的元素在原数组的位置。

>> [ignore,p] = sort(y)ignore = 0.0099 0.0579 0.3529 0.4103 0.8132 0.8936p = 6 3 4 1 5 2

rand默认升序排序。而最小的0.0099在原数组的位置是6,所以位置数组第一个值为6。

把位置数组p返回,就得到了1到n的无序数组。

但是如果传入两个参数,randperm[a,b]
实现的是从1~a中随机产生b个不重复的整数。
而我要实现的,就是双参数的形式。

那么接下来要看c++的实现:
参照百度百科中的实现思路

#include <algorithm>#include <vector>void randperm(){vector<int> numbres;for (int i = 0; i < 100; i++){numbres.push_back(i);}std::random_shuffle(numbres.begin(), numbres.end());for (int j = 0; j < 10; j++){cout << numbres[j] << endl;}}

生成100个随机数,打乱后取前10个。即完成了从1-100中随机取10个数的功能。

除此之外,还有很多方法。

参考:
https://www.jianshu.com/p/fd23141df09a
https://www.cnblogs.com/salan668/p/3652532.html
https://blog.csdn.net/andy_songlin/article/details/6552674
https://www.cnblogs.com/afarmer/archive/2011/05/01/2033715.html

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。