Convert MATLAB Code to Python Code (.ipynb)

10 views (last 30 days)
Mujtaba Farrukh on 12 May 2022
Answered: Al Danial on 21 May 2022
Objective : Conversion of MATLAB code to Python Code
Hi,
I want to convert a really small and short code of MATLAB (.m) to Python (.ipynb).
Following is the code:
%% CLEARING THE PARAMETERS
clc;
clear;
close all;
%% PROGRAM
N=500;
M=double(diag(ones(1,N-1),1) | diag(ones(1,N-1),-1));
v=ones(1,N)*-2;
n = size(M,1);
M(1:(n+1):end) = v;
vec=inv(M)*ones(N,1);
x=1/(N+1):1/(N+1):1-1/(N+1);
plot(x,vec,'r','LineWidth',3)
xlabel('x values')
ylabel('vector')
grid minor
axis tight
Please can anyone tell me how to do it?

Al Danial on 21 May 2022
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
N = 500
M = np.diag(np.ones((N-1,)),1) + np.diag(np.ones((N-1,)),-1)
v = np.ones((N,))*-2
M += np.diag(v)
vec = np.linalg.inv(M).dot(np.ones((N,)))
x = np.linspace(1/(N+1), 1 - 1/(N+1), N)
plt.plot(x,vec,'r', linewidth=3)
plt.xlabel('x values')
plt.ylabel('vector')
plt.grid()
plt.show()

Categories

Find more on Call Python from MATLAB in Help Center and File Exchange

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!