python VS matlab: reshape/max/matrix index等方法比较
matlab是进行学术研究必备的工具软件,python是进行工程实践的必备软件。因为matlab中矩阵运算的方便高效,有些代码前期会在matlab中编写,后面再转到python。在转换的过程中,发现matlab和python中一些功能函数的不同,现总结如下,欢迎大家批评指正!
1.reshape
- matlab
reshape(1:12,3,4)
- python
a = np.array(range(1,13)).reshape(-1,4)print(a)
对比发现,matlab和python对数组的存储方式不同,==前者按列,后者按行。==
python中要得到同matlab的数组,可通过矩阵转置实现:
对于高维数组,通过矩阵转置就不方便了,在matlab中可以通过permute函数实现矩阵维度的交换:
%% 2D
data2D = reshape(1:12,3,4)
data2D = permute(data2D,[2,1])%% 3D
data3D = reshape(1:12,3,2,2) % 维度顺序为:1,2,3
data3D = permute(data3D,[3,2,1]) % 即实现1,3维度置换,为 2*2*3. ps:可以再测试[3,1,2]
对于在图像频率滤波和光度立体的基于Fourier基函数深度估计中应用广泛的FFT,同样存在matlab、python的主轴不同问题。
对于三维数组的FFT变换,转换方式如下:
data = reshape(1:12,3,2,2)
% newdata = permute(data,[3,2,1])
%% 除了用permute函数,也可以自定义实现
newdata = zeros(2,2,3);
for i = 1:2for j = 1:2newdata(j,i,:) = data(:,i,j); % 转置end
end
newdata
fft(newdata)
data = np.array(range(1,13)).reshape(-1,2,3)print(data)print(np.fft.fft(data))print(np.fft.fft(data,axis=0))
2.max
- matlab
clc
close all
clear allTestMaxfunction TestMax()
%% scalar
res = max(6,[1 4 6 7 9 0 3]) % 逐个比较,输出数组
res = max(3,[1+i,2-2i,3+4i,4-6i,-i,5-2i]) % 只与复数的实部比较
res = max(1+3i,[2+3i,2-2i,3+4i,4-6i,3-i,5-2i]) % 按照模长比较data = [1+i,2-2i,3+4i,4-6i,-i,5-2i;2+3i,2-2i,3+4i,4-6i,3-i,5-2i]
data(1) = 0 % 数组在matlab中按列存储,每个元素对应一个索引,将第一个元素设为0,与data(1,:)相区别end
def TestMax():# res = max(3,np.array([1,4,6,7,9,0,3])) # error# res = np.max(3,np.array([1,4,6,7,9,0,3])) # error# res = np.maximum(3,np.array([1,4,6,7,9,0,3])) # 同matlab中 max# res = np.maximum(3,np.array([1-1j,4+1j,6-2j,7,9+3j,0-2j,3-1j])) # 同matlab中 maxres = np.maximum(3+1j,np.array([1-1j,4+1j,6-2j,7,9+3j,0-2j,3-1j])) # 同matlab中 maxprint(res)data = np.array([[1+1j,2-2j,3+4j,4-6j,-1j,5-2j],[2+3j,2-2j,3+4j,4-6j,3-1j,5-2j]])data[0] = 0 # 结果同data[0,:] 将第一行全设为0print(data)
3.index
matlab是矩阵实验室(Matrix laboratory)的简称,原就是为了方便高效进行矩阵运算而开发。特点是矩阵index从1开始,支持end操作,矩阵的切片操作十分简便。
以矩阵的中心差分说明numpy包和matlab在矩阵操作上的异同。
- matlab
function TestIndex()img = imread('demoshape.png');if(numel(size(img)) > 2)img = rgb2gray(img);end%% 与原图不同大小px = img(2:end,:) - img(1:end-1,:); % 数据类型均为uint8, 负数强制为0. python中负数强制为其补数qy = img(:,2:end) - img(:,1:end-1);%% 与原图相同大小ppx = img([2:end end],:) - img([1 1:end-1],:);qqy = img(:,[2:end end]) - img(:,[1 1:end-1]);figuresubplot(231)imshow(img)subplot(232)imshow(px)subplot(233)imshow(qy)subplot(234)imshow(ppx)subplot(235)imshow(qqy)canny = edge(img,'canny',0.1);subplot(236)imshow(canny)
end
matlab的imshow函数显示的原因,有些细节需要放大才会显示清楚,建议自己运行下代码查看结果。
- python
关键在于如何在python中方便高效地表达矩阵的索引操作:
- end - k 的表达
- k:end,m:end - k的表达
def CalcImgDiff(imglight,imgdark,opt: int = 0):assert imglight.shape == imgdark.shapeH,W = imglight.shapeimgdiff = np.zeros_like(imglight,dtype=np.uint8)if opt == 0:return imglight - imgdarkelif opt == 1:for i in range(H):for j in range(W):if imglight[i,j] > imgdark[i,j]:imgdiff[i,j] = imglight[i,j] - imgdark[i,j]elif opt == 2:for i in range(H):for j in range(W):imgdiff[i, j] = abs(imglight[i, j] - imgdark[i, j])return imgdiffdef TestIndex():img = cv2.imread('./imgs/others/img/demoshape.png',0)# img_ref = scio.loadmat('./imgs/others/img/demoshape_img.mat')['img']# px_ref = scio.loadmat('./imgs/others/img/demoshape_px.mat')['px']# qy_ref = scio.loadmat('./imgs/others/img/demoshape_qy.mat')['qy']# ppx_ref = scio.loadmat('./imgs/others/img/demoshape_ppx.mat')['ppx']# qqy_ref = scio.loadmat('./imgs/others/img/demoshape_qqy.mat')['qqy']img = cv2.resize(img,(400,300))H,W = img.shapeimglight = img[1:H, :]imgdark = img[0:H - 1, :]px = CalcImgDiff(imglight,imgdark,0)imglight = img[:,1:W]imgdark = img[:,0:W-1]qy = CalcImgDiff(imglight, imgdark,0)# 关键如何表达 [1:end end]row_former_index = list(range(0, H - 1))row_former_index.insert(0, 0)row_latter_index = list(range(1, H))row_latter_index.append(-1)col_former_index = list(range(0, W - 1))col_former_index.insert(0, 0)col_latter_index = list(range(1, W))col_latter_index.append(-1)imglight = img[row_latter_index, :]imgdark = img[row_former_index, :]ppx = CalcImgDiff(imglight,imgdark,0)imglight = img[:, col_latter_index]imgdark = img[:, col_former_index]qqy = CalcImgDiff(imglight,imgdark,0)plt.figure()plt.subplot(231)plt.imshow(img,cmap=plt.cm.gray,vmin=0,vmax=255)plt.subplot(232)plt.imshow(px,cmap=plt.cm.gray,vmin=0,vmax=255)plt.subplot(233)plt.imshow(qy,cmap=plt.cm.gray,vmin=0,vmax=255)plt.subplot(234)plt.imshow(ppx,cmap=plt.cm.gray,vmin=0,vmax=255)plt.subplot(235)plt.imshow(qqy,cmap=plt.cm.gray,vmin=0,vmax=255)canny = cv2.Canny(img,1,255)plt.subplot(236)plt.imshow(canny,cmap=plt.cm.gray,vmin=0,vmax=255)plt.show()
总结:
matlab: index从1开始,python: index从0开始
matlab:m:n,列表结果包含n,python:m:n,列表结果不含n
具体表达如下,其中 i∈N+;j,k∈Ni\in \mathbb{N^+}; j, k \in \mathbb{N} i∈N+;j,k∈N
- matlab:A(end-k,:) python : A[H - k - 1,:]
- matlab: A(i:end-j,:) python : A[i - 1:H - j,:]
python VS matlab: reshape/max/matrix index等方法比较相关推荐
- matlab中max函数的使用方法详细介绍(附matlab代码)
一.语句 max 数组的最大元素 1.M = max(A) 返回数组的最大元素. 如果 A 是向量,则 max(A) 返回 A 的最大值. 如果 A 为矩阵,则 max(A) 是包含每一列的最大值的行 ...
- 聚类的外部指标(Purity, ARI, NMI, ACC) 和内部指标(NCC,Entropy,Compactness,Silhouette Index),附代码 (Python 和 Matlab)
聚类性能评估的外部指标和内部指标,附代码 (Python 和 Matlab) 文章目录 聚类性能评估的外部指标和内部指标,附代码 (Python 和 Matlab) 1 外部指标 1.1 Purity ...
- 基于python与matlab的TOA定位算法性能仿真
基于python与matlab的TOA定位算法性能仿真 仿真要求 仿真方案的设计 matlab仿真代码 python仿真代码 仿真结果 仿真要求 要求一:编写两个函数TOA_LLOP和TOA_CHAN ...
- 范德蒙德矩阵在MATLAB中怎么表示,Python 之 Python与MATLAB 矩阵操作总结
Python 之 Python与MATLAB 矩阵操作小结 一.线形代数理论基础 线形代数(linear algebra)是数学的一个分支,研究矩阵理论.向量空间.线性变换和有限维线形方程组等内容. ...
- grs matlab公式,[转载]matlab中Max的用法(转)
Matlab中max函数在矩阵中求函数大小的实例如下: C = max(A) 返回一个数组各不同维中的最大元素. 如果A是一个向量,max(A)返回A中的最大元素. 如果A是一个矩阵,max(A)将A ...
- 科学计算:Python VS. MATLAB(3)----线性代数基础
科学计算:Python VS. MATLAB(3)----线性代数基础 按:在介绍工具之前先对理论基础进行必要的回顾是很必要的.没有理论的基础,讲再多的应用都是空中楼阁.本文主要设涉及线性代数和矩阵论 ...
- LeetCode 566 Reshape the Matrix 解题报告
题目要求 In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a ...
- Python实现MATLAB bi2de函数
Python实现MATLAB bi2de函数 主要功能是将二进制数组转为十进制数 此文章用Python实现了bi2de函数的第一个功能 MATLB解释 %BI2DE Convert binary ve ...
- leetcode讲解--566. Reshape the Matrix
题目 In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a ne ...
最新文章
- golang int 转string_Golang的逃逸分析
- Swift中的集合类之数组
- 使用CSS3属性aspect-ratio做横屏检测优化用户体验,附demo完整代码
- go语言之进阶篇主协程先退出导致子协程没来得及调用
- docker开放的端口_关于docker自动开放端口解决方案
- WPF调用图片路径,或资源图片
- slack 聊天机器人_使用Node.js和Symanto的Text Analytics API在Slack中创建情感机器人
- html节点替换代码,html之DOM对象replaceChild()方法(子节点替换)功能简介说明
- miui tv android,MIUI for TV 3.0上线 应用远程安装 手机反控电视
- 什么是RS232电平?什么是TTL电平?
- 好玩的海外游戏集结,有没有你玩过的?
- 0321 预习笔记直播笔记
- 申请微信小程序需要的材料
- C语言实现计算数字能否被3个数整除
- 【Android App】实战项目之虚拟现实(VR)的全景相册(附源码和演示视频 可用于学习和大作业)
- GitHub Pages + Hexo搭建个人博客网站,史上最全教程
- 51cto——让梦飞翔
- 21考研,这些事情千万不要做!
- esp-12s WiFi模块连接 stm32f4单片机与电脑数据传输
- 网页图片实现百叶窗效果
热门文章
- 百科知识 ass文件如何打开
- Apache配置文件中Order Allow Deny笔记心得
- vue组件库大全(忘了的时候可以进来找一下~)
- Python数据分析2-pandas入门和实战
- 5元的小乌龟吃什么_小乌龟吃什么?小乌龟怎么养经验详解
- Android事件总线 EventBus3.0用法学习
- MyBatis-Plus 扩展篇 > 自动填充功能
- bin/hive出错:Exception in thread main java.lang.RuntimeException: java.net.ConnectException: Call Fr
- 【多任务学习】Modeling Task Relationships in Multi-task Learning with Multi-gate Mixture-of-Experts KDD18
- 标准差和均方根误差的区别