matlab读取txt数据绘图(python命令行传参)

(1)命令行实现高斯分布

一:综述

Python唯一支持的参数传递方式是『共享传参』(call by sharing)多数面向对象语言都采用这一模式,包括Ruby、Smalltalk和Java(Java的引用类型是这样,基本类型按值传递)共享传参是指函数的各个形式参数获得实参中各个引用的副本;也就是说,函数内部的形参是实参的别名(alias)这种方案的结果是,函数可能会修改作为参数传入的可变对象,但是无法修改那些对象的标识(即不能把一个对象替换为另一个对象)

二:所需函数介绍

  1. numpy.random.uniform(low,high,size)
    

    从一个均匀分布[low,high)中随机采样,注意定义域是左闭右开,即包含low,不包含high.

  2. getopt.getopt( [命令行参数列表], "短选项", [长选项列表] )
    

    该函数返回两个值. opts 和args

    opts 是一个存有所有选项及其输入值的元组.当输入确定后,这个值不能被修改了.

    args 是去除有用的输入以后剩余的部分.

  3. count, bins, ignored = plt.hist(rand_data, 30, density=True)
    

    rand_data:数据

    bins:直方图绘图的列数

    density=True:把数据转为密度直方图

    count : 数组或数组列表百分比

    ignored : 列表 或者列表的列表 图形对象

三:python代码

1.需求分析

该代码主要通过命令行传参的方式实现高斯模型,将图像和数据导入本地txt文件

2.代码
# 导入必要的库
import numpy as np
import pandas as pd
import matplotlib.pylab as plt
import sys
import getopt
from scipy import stats
#import em

mu=1
sigma = 3  # 标准差为3
num = 10000  # 个数为10000

argc = len(sys.argv)
opts, args = getopt.getopt(sys.argv[1:], "hdp", ["help", "data=", "png="])
if argc>1:
    #np.random.seed(100)  # 固定随机数种子,确保下次运行数据相同
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            print('请输入正确的参数\n'
                  '-d 代表生成高斯分布数据保存到本地文件\n'
                  '-p 代表画出高斯分布图\n'
                  '如python test04.py -p\n'
                  'python test04.py -d')
            sys.exit()
        elif opt in ("-d", "--data"):
            #username = arg
            #mu = eval(arg)  # 男生
            #sigma = 3  # 标准差为3
            #num = 10000  # 个数为10000
            rand_data = np.random.normal(mu, sigma, num)
            count, bins, ignored = plt.hist(rand_data, 30, density=True)

            # 前面省略,从下面直奔主题:
            data = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(- (bins - mu) ** 2 / (2 * sigma ** 2))

            file = open('results_storage.txt', 'a')
            # i=0
            #保存到本地txt文件
            for i in range(len(data)):
                # s = str(bins[i]).replace('[',").replace('[',")+'\t'+str(data[i]).replace('[',").replace('[',")#去除[],这两行按数据不同,可以选择
                s = str(bins[i]).replace('[', ").replace('[',") + ' ' + str(data[i]).replace('[', ").replace('[',")
                s = s.replace("'", ").replace(',',") + '\n'  # 去除单引号,逗号,每行末尾追加换行符
                file.write(s)
            file.close()
        elif opt in ("-p", "--png"):
            #password = arg
            #mu = eval(arg)


            rand_data = np.random.normal(mu, sigma, num)
            count, bins, ignored = plt.hist(rand_data, 30, density=True)
            plt.plot(bins, 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(- (bins - mu) ** 2 / (2 * sigma ** 2)),
                     linewidth=2, color='r')
            plt.show()
    # arg1 = sys.argv[1]


else:
    print('运行错误!请输入正确的参数\n'
          '如python test04.py -p \n'
          'python test03.py -d ')


#python test04.py -p

四:结果显示

1.参数不足
python test04.py
运行错误!请输入正确的参数
如python test04.py -p
python test03.py -d

在这里插入图片描述

2.请求帮助
python test04.py --help
请输入正确的参数
-d 代表生成高斯分布数据保存到本地文件
-p 代表画出高斯分布图
如python test04.py -p
python test04.py -d

在这里插入图片描述

3.生成图像
python test04.py -p                      

在这里插入图片描述

4.生成数据保存
python test04.py -d

在这里插入图片描述

(2)matlab读取数据验证

一:需求分析

将python生成的数据保存到results_storage.txt,利用matlab读取数据绘图。

二:matlab代码

matlab_data.m

results_storage.txt

clc
clear
date=load('G:\python\GMM\results_storage.txt');
x=date(:,1);
y=date(:,2);
plot(x,y,'r');
xlabel('x');ylabel('y');
%axis([0 80 0 30]);
hold on

三:结果显示

在这里插入图片描述

与python画的图像一致

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

唐维康

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值