【Array】73. Set Matrix Zeroes


class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
    	if(matrix.size()==0)
    		return;
    	int flag=0;
    	for(int i=0;i<matrix.size();i++)
    	{
    		for(int j=0;j<matrix[0].size();j++)
    		{
    			if(matrix[i][j]==0)
    			{
    				matrix[i][0]=0;
    				if(j==0)
    					flag=1; //标记第一列是否置零
    				else
    					matrix[0][j]=0;
    			}
    		}
    	}

        for(int i=1;i<matrix[0].size();i++)
    	{
    		if(matrix[0][i]==0)
    		{
    			for(int j=1;j<matrix.size();j++)
    				matrix[j][i]=0;
    		}
    	}  //col先置零
    	for(int i=0;i<matrix.size();i++)
    	{
    		if(matrix[i][0]==0)
    		{
    			for(int j=1;j<matrix[0].size();j++)
    				matrix[i][j]=0;
    		}
    	} //row置零

    	if(flag)
    	{
    		for(int j=0;j<matrix.size();j++)
    				matrix[j][0]=0;
    	} //第一列置零
    }
};

""" This code is supported by the website: https://www.guanjihuan.com The newest version of this code is on the web page: https://www.guanjihuan.com/archives/24059 """ import numpy as np from math import * import cmath import math def hamiltonian(k1, k2, t1=2.82, a=1/sqrt(3)): # 石墨烯哈密顿量(a为原子间距,不赋值的话默认为1/sqrt(3)) h = np.zeros((2, 2), dtype=complex) h[0, 0] = 0.28/2 h[1, 1] = -0.28/2 h[1, 0] = t1*(cmath.exp(1j*k2*a)+cmath.exp(1j*sqrt(3)/2*k1*a-1j/2*k2*a)+cmath.exp(-1j*sqrt(3)/2*k1*a-1j/2*k2*a)) h[0, 1] = h[1, 0].conj() return h def main(): k_array, berry_curvature_array = calculate_berry_curvature_with_efficient_method(hamiltonian_function=hamiltonian, k_min=-2*math.pi, k_max=2*math.pi, precision=500, print_show=0) plot_3d_surface(k_array, k_array, np.real(berry_curvature_array[:, :, 0]), title='Valence Band', xlabel='kx', ylabel='ky', zlabel='Berry curvature') plot_3d_surface(k_array, k_array, np.real(berry_curvature_array[:, :, 1]), title='Conductance Band', xlabel='kx', ylabel='ky', zlabel='Berry curvature') dim = berry_curvature_array.shape plot(k_array, np.real(berry_curvature_array[int(dim[0]/2), :, 0]), title='Valence Band ky=0', xlabel='kx', ylabel='Berry curvature') # ky=0 plot(k_array, np.real(berry_curvature_array[int(dim[0]/2), :, 1]), title='Conductance Band ky=0', xlabel='kx', ylabel='Berry curvature') # ky=0 # import guan # k_array, berry_curvature_array = guan.calculate_berry_curvature_with_efficient_method(hamiltonian_function=hamiltonian, k_min=-2*math.pi, k_max=2*math.pi, precision=500, print_show=0) # guan.plot_3d_surface(k_array, k_array, np.real(berry_curvature_array[:, :, 0]), title='Valence Band', xlabel='kx', ylabel='ky', zlabel='Berry curvature') # guan.plot_3d_surface(k_array, k_array, np.real(berry_curvature_array[:, :, 1]), title='Conductance Band', xlabel='kx', ylabel='ky', zlabel='Berry curvature') # dim = berry_curvature_array.shape # guan.plot(k_array, np.real(berry_curvature_array[int(dim[0]/2), :, 0]), title='Valence Band ky=0', xlabel='kx', ylabel='Berry curvature') # ky=0 # guan.plot(k_array, np.real(berry_curvature_array[int(dim[0]/2), :, 1]), title='Conductance Band ky=0', xlabel='kx', ylabel='Berry curvature') # ky=0 def calculate_berry_curvature_with_efficient_method(hamiltonian_function, k_min=-math.pi, k_max=math.pi, precision=100, print_show=0): if np.array(hamiltonian_function(0, 0)).shape==(): dim = 1 else: dim = np.array(hamiltonian_function(0, 0)).shape[0] delta = (k_max-k_min)/precision k_array = np.arange(k_min, k_max, delta) berry_curvature_array = np.zeros((k_array.shape[0], k_array.shape[0], dim), dtype=complex) i0 = 0 for kx in k_array: if print_show == 1: print(kx) j0 = 0 for ky in k_array: H = hamiltonian_function(kx, ky) eigenvalue, vector = np.linalg.eigh(H) H_delta_kx = hamiltonian_function(kx+delta, ky) eigenvalue, vector_delta_kx = np.linalg.eigh(H_delta_kx) H_delta_ky = hamiltonian_function(kx, ky+delta) eigenvalue, vector_delta_ky = np.linalg.eigh(H_delta_ky) H_delta_kx_ky = hamiltonian_function(kx+delta, ky+delta) eigenvalue, vector_delta_kx_ky = np.linalg.eigh(H_delta_kx_ky) for i in range(dim): vector_i = vector[:, i] vector_delta_kx_i = vector_delta_kx[:, i] vector_delta_ky_i = vector_delta_ky[:, i] vector_delta_kx_ky_i = vector_delta_kx_ky[:, i] Ux = np.dot(np.conj(vector_i), vector_delta_kx_i)/abs(np.dot(np.conj(vector_i), vector_delta_kx_i)) Uy = np.dot(np.conj(vector_i), vector_delta_ky_i)/abs(np.dot(np.conj(vector_i), vector_delta_ky_i)) Ux_y = np.dot(np.conj(vector_delta_ky_i), vector_delta_kx_ky_i)/abs(np.dot(np.conj(vector_delta_ky_i), vector_delta_kx_ky_i)) Uy_x = np.dot(np.conj(vector_delta_kx_i), vector_delta_kx_ky_i)/abs(np.dot(np.conj(vector_delta_kx_i), vector_delta_kx_ky_i)) berry_curvature = cmath.log(Ux*Uy_x*(1/Ux_y)*(1/Uy))/delta/delta*1j berry_curvature_array[j0, i0, i] = berry_curvature j0 += 1 i0 += 1 return k_array, berry_curvature_array def plot_3d_surface(x_array, y_array, matrix, xlabel='x', ylabel='y', zlabel='z', title='', fontsize=20, labelsize=15, show=1, save=0, filename='a', file_format='.jpg', dpi=300, z_min=None, z_max=None, rcount=100, ccount=100): import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator matrix = np.array(matrix) fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) plt.subplots_adjust(bottom=0.1, right=0.65) x_array, y_array = np.meshgrid(x_array, y_array) if len(matrix.shape) == 2: surf = ax.plot_surface(x_array, y_array, matrix, rcount=rcount, ccount=ccount, cmap=cm.coolwarm, linewidth=0, antialiased=False) elif len(matrix.shape) == 3: for i0 in range(matrix.shape[2]): surf = ax.plot_surface(x_array, y_array, matrix[:,:,i0], rcount=rcount, ccount=ccount, cmap=cm.coolwarm, linewidth=0, antialiased=False) ax.set_title(title, fontsize=fontsize, fontfamily='Times New Roman') ax.set_xlabel(xlabel, fontsize=fontsize, fontfamily='Times New Roman') ax.set_ylabel(ylabel, fontsize=fontsize, fontfamily='Times New Roman') ax.set_zlabel(zlabel, fontsize=fontsize, fontfamily='Times New Roman') ax.zaxis.set_major_locator(LinearLocator(5)) ax.zaxis.set_major_formatter('{x:.2f}') if z_min!=None or z_max!=None: if z_min==None: z_min=matrix.min() if z_max==None: z_max=matrix.max() ax.set_zlim(z_min, z_max) ax.tick_params(labelsize=labelsize) labels = ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels() [label.set_fontname('Times New Roman') for label in labels] cax = plt.axes([0.8, 0.1, 0.05, 0.8]) cbar = fig.colorbar(surf, cax=cax) cbar.ax.tick_params(labelsize=labelsize) for l in cbar.ax.yaxis.get_ticklabels(): l.set_family('Times New Roman') if save == 1: plt.savefig(filename+file_format, dpi=dpi) if show == 1: plt.show() plt.close('all') def plot(x_array, y_array, xlabel='x', ylabel='y', title='', fontsize=20, labelsize=20, show=1, save=0, filename='a', file_format='.jpg', dpi=300, style='', y_min=None, y_max=None, linewidth=None, markersize=None, adjust_bottom=0.2, adjust_left=0.2): import matplotlib.pyplot as plt fig, ax = plt.subplots() plt.subplots_adjust(bottom=adjust_bottom, left=adjust_left) ax.grid() ax.tick_params(labelsize=labelsize) labels = ax.get_xticklabels() + ax.get_yticklabels() [label.set_fontname('Times New Roman') for label in labels] ax.plot(x_array, y_array, style, linewidth=linewidth, markersize=markersize) ax.set_title(title, fontsize=fontsize, fontfamily='Times New Roman') ax.set_xlabel(xlabel, fontsize=fontsize, fontfamily='Times New Roman') ax.set_ylabel(ylabel, fontsize=fontsize, fontfamily='Times New Roman') if y_min!=None or y_max!=None: if y_min==None: y_min=min(y_array) if y_max==None: y_max=max(y_array) ax.set_ylim(y_min, y_max) if save == 1: plt.savefig(filename+file_format, dpi=dpi) if show == 1: plt.show() plt.close('all') if __name__ == '__main__': main()这是在干嘛
07-10
import numpy as np import pandas as pd import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ["SimHei"] # 单使用会使负号显示错误 plt.rcParams['axes.unicode_minus'] = False # 把负号正常显示 # 读取北京房价数据 path = 'data.txt' data = pd.read_csv(path, header=None, names=['房子面积', '房子价格']) print(data.head(10)) print(data.describe()) # 绘制散点图 data.plot(kind='scatter', x='房子面积', y='房子价格') plt.show() def computeCost(X, y, theta): inner = np.power(((X * theta.T) - y), 2) return np.sum(inner) / (2 * len(X)) data.insert(0, 'Ones', 1) cols = data.shape[1] X = data.iloc[:,0:cols-1]#X是所有行,去掉最后一列 y = data.iloc[:,cols-1:cols]#X是所有行,最后一列 print(X.head()) print(y.head()) X = np.matrix(X.values) y = np.matrix(y.values) theta = np.matrix(np.array([0,0])) print(theta) print(X.shape, theta.shape, y.shape) def gradientDescent(X, y, theta, alpha, iters): temp = np.matrix(np.zeros(theta.shape)) parameters = int(theta.ravel().shape[1]) cost = np.zeros(iters) for i in range(iters): error = (X * theta.T) - y for j in range(parameters): term = np.multiply(error, X[:, j]) temp[0, j] = theta[0, j] - ((alpha / len(X)) * np.sum(term)) theta = temp cost[i] = computeCost(X, y, theta) return theta, cost alpha = 0.01 iters = 1000 g, cost = gradientDescent(X, y, theta, alpha, iters) print(g) print(computeCost(X, y, g)) x = np.linspace(data.Population.min(), data.Population.max(), 100) f = g[0, 0] + (g[0, 1] * x) fig, ax = plt.subplots(figsize=(12,8)) ax.plot(x, f, 'r', label='Prediction') ax.scatter(data.Population, data.Profit, label='Traning Data') ax.legend(loc=2) ax.set_xlabel('房子面积') ax.set_ylabel('房子价格') ax.set_title('北京房价拟合曲线图') plt.show()
06-04
提供了基于BP(Back Propagation)神经网络结合PID(比例-积分-微分)控制策略的Simulink仿真模型。该模型旨在实现对杨艺所著论文《基于S函数的BP神经网络PID控制器及Simulink仿真》中的理论进行实践验证。在Matlab 2016b环境下开发,经过测试,确保能够正常运行,适合学习和研究神经网络在控制系统中的应用。 特点 集成BP神经网络:模型中集成了BP神经网络用于提升PID控制器的性能,使之能更好地适应复杂控制环境。 PID控制优化:利用神经网络的自学习能力,对传统的PID控制算法进行了智能调整,提高控制精度和稳定性。 S函数应用:展示了如何在Simulink中通过S函数嵌入MATLAB代码,实现BP神经网络的定制化逻辑。 兼容性说明:虽然开发于Matlab 2016b,但理论上兼容后续版本,可能会需要调整少量配置以适配不同版本的Matlab。 使用指南 环境要求:确保你的电脑上安装有Matlab 2016b或更高版本。 模型加载: 下载本仓库到本地。 在Matlab中打开.slx文件。 运行仿真: 调整模型参数前,请先熟悉各模块功能和输入输出设置。 运行整个模型,观察控制效果。 参数调整: 用户可以自由调节神经网络的层数、节点数以及PID控制器的参数,探索不同的控制性能。 学习和修改: 通过阅读模型中的注释和查阅相关文献,加深对BP神经网络与PID控制结合的理解。 如需修改S函数内的MATLAB代码,建议有一定的MATLAB编程基础。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值