Tag Archives: matlab
Solve a pde equation with finite differences for Simulink
Hello , I want to transform this code that solves a pde equation with the ode solver into finite diferences, because I want to take the code as a matlab function block in simulink so it stands no ode solver(since it is an iterator take much time every time step so never ends simulation ) thats why i want to take it into finite differences .The equations are the following
The inital code is the following with ode solver:
L = 20 ; % Longitud del lecho (m)
eps = 0.4; % Porosidad
u = 0.2; % Velocidad superficial del fluido (m/s)
k_f = 0.02; % Constante de transferencia de masa (1/s)
c0 = 0;
Kf = 4; % Constante de Freundlich
rhop = 1520;
n = 2; % Exponente de Freundlich
% Concentración inicial del fluido (kg/m³)
q0 = 4.320; % Concentración inicial en el sólido (kg/m³)
% Densidad del adsorbente (kg/m³)
tf = 10; % Tiempo final de simulación (horas)
Nt = 100;
t = linspace(0, tf*3600, Nt);
Nz = 100;
z = linspace(0, L,Nz);
dz = z(2) – z(1);
% Initial conditions
ICA = max(ones(1, Nz) * c0, 1e-12); % Evitar valores negativos o cero
ICB = ones(1, Nz) * q0;
IC = [ICA ICB];
options = odeset(‘RelTol’, 1e-6, ‘AbsTol’, 1e-8, ‘InitialStep’, 1e-4, ‘MaxStep’, 100);
[t, y] = ode15s(@fun_pde, t, IC, options, Nz, eps, n, Kf, k_f, u, rhop, dz);
% Define value
cc = y(:, 1:Nz);
qq = y(:, Nz+1:end);
% Recalculate new limit conditions
cc(:, 1) = 0;
cc(:, end) = cc(:, end-1);
% Plotting
cp = cc(:, end) ./ c0;
qp = qq(:, 🙂 ./ q0;
%q_promedio = mean(qq, 2); % Promedio de q en el lecho para cada instante de tiempo
%conversion = 1 – (q_promedio / q0); % Conversión normalizada
figure;
subplot(2, 1, 1);
time = t / 3600; % Convertir a horas
plot(time, 1- qp, ‘b’, ‘LineWidth’, 1.5);
xlabel(‘Tiempo (horas)’);
ylabel(‘Conversion’);
title(‘Curva de conversión durante la desorción’);
grid on;
subplot(2, 1, 2);
plot(t / 3600, (cc(:,:)), ‘LineWidth’, 1.5);
xlabel(‘Tiempo (horas)’);
ylabel(‘Soluciòn kg/m3’);
title(‘Curva de carga de la solucion durante la desorciòn’);
grid on;
% PDE function
function dydt = fun_pde(~, y, Nz, eps, n, Kf, k_f, u, rhop, dz)
dcdt = zeros(Nz, 1);
dqdt = zeros(Nz, 1);
c = y(1:Nz);
q = y(Nz+1:2*Nz);
% Boundary conditions
c(1) = max(c(1), 0); % Asegurar que c(1) sea no negativo
c(end) = c(end-1); % Asegurar que c(1) sea no negativo
% Interior nodes
qstar = zeros(Nz, 1);
dcdz = zeros(Nz, 1);
for i = 2:Nz-1
qstar(i) = Kf .* max(c(i), 1e-12).^(1/n); % Evitar problemas numéricos
dqdt(i) = k_f .* (qstar(i) – q(i));
% if i < Nz
dcdz(i) = (c(i+1) – c(i-1)) / (2 * dz);
%else
% dcdz(i) = (c(i) – c(i-1)) / dz;
%end
dcdt(i) = -u * dcdz(i) – rhop * ((1 – eps) / eps) .* dqdt(i);
end
dydt = [dcdt; dqdt];
end
next is a try to solve with finite diferences but get someting different:
L = 20 ; % Longitud del lecho (m)
eps = 0.4; % Porosidad
u = 0.2; % Velocidad superficial del fluido (m/s)
k_f = 0.02; % Constante de transferencia de masa (1/s)
c0 = 0;
Kf = 4; % Constante de Freundlich
rhop = 1520;
n = 2; % Exponente de Freundlich
% Concentración inicial del fluido (kg/m³)
q0 = 4.320; % Concentración inicial en el sólido (kg/m³)
% Densidad del adsorbente (kg/m³)
tf = 10; % Tiempo final de simulación (horas)
Nz = 100; % Número de nodos espaciales
% Discretización espacial y temporal
z = linspace(0, L, Nz);
t = linspace(0, tf*3600, Nt);
dz = z(2) – z(1);
dt = t(2) – t(1); % Paso temporal
% Condiciones iniciales
c = ones(Nt, Nz) * c0; % Concentración en el fluido
q = ones(Nt, Nz) * q0; % Concentración en el sólido
% Iteración en el tiempo (Diferencias Finitas Explícitas)
for ti = 1:Nt-1
for zi = 2:Nz-1
% Isoterma de Freundlich
qstar = Kf * max(c(ti, zi), 1e-12)^(1/n);
% Transferencia de masa (Desorción)
dqdt = k_f * (qstar – q(ti, zi));
% Gradiente espacial de concentración (Diferencias centradas)
dcdz = (c(ti, zi+1) – c(ti, zi-1)) / (2 * dz);
% Ecuación de balance de masa en el fluido
dcdt = -u * dcdz – rhop * ((1 – eps) / eps) * dqdt;
% Actualizar valores asegurando que sean positivos
c(ti+1, zi) = max(c(ti, zi) + dcdt * dt, 0);
q(ti+1, zi) = max(q(ti, zi) + dqdt * dt, 0);
end
end
% Condiciones de frontera
c(:, 1) = c0; % Entrada con concentración baja
c(:, Nz) = c(:, Nz-1); % Gradiente nulo en la salida
% Cálculo de la conversión normalizada
qp = q(:, 🙂 ./ q0;
% Graficar resultados
figure;
subplot(2, 1, 1);
plot(t / 3600, 1-qp, ‘b’, ‘LineWidth’, 1.5);
xlabel(‘Tiempo (horas)’);
ylabel(‘Conversion’);
title(‘Curva de conversión durante la desorción’);
grid on;
subplot(2, 1, 2);
c_salida = c(:, :); % Concentración en la salida del lecho
plot(t / 3600, c_salida, ‘r’, ‘LineWidth’, 1.5);
xlabel(‘Tiempo (horas)’);
ylabel(‘Soluciòn kg/m3’);
title(‘Curva de carga de la solucion durante la desorciòn’);
grid on;
I dont know why is wrong
Thanks in advanceHello , I want to transform this code that solves a pde equation with the ode solver into finite diferences, because I want to take the code as a matlab function block in simulink so it stands no ode solver(since it is an iterator take much time every time step so never ends simulation ) thats why i want to take it into finite differences .The equations are the following
The inital code is the following with ode solver:
L = 20 ; % Longitud del lecho (m)
eps = 0.4; % Porosidad
u = 0.2; % Velocidad superficial del fluido (m/s)
k_f = 0.02; % Constante de transferencia de masa (1/s)
c0 = 0;
Kf = 4; % Constante de Freundlich
rhop = 1520;
n = 2; % Exponente de Freundlich
% Concentración inicial del fluido (kg/m³)
q0 = 4.320; % Concentración inicial en el sólido (kg/m³)
% Densidad del adsorbente (kg/m³)
tf = 10; % Tiempo final de simulación (horas)
Nt = 100;
t = linspace(0, tf*3600, Nt);
Nz = 100;
z = linspace(0, L,Nz);
dz = z(2) – z(1);
% Initial conditions
ICA = max(ones(1, Nz) * c0, 1e-12); % Evitar valores negativos o cero
ICB = ones(1, Nz) * q0;
IC = [ICA ICB];
options = odeset(‘RelTol’, 1e-6, ‘AbsTol’, 1e-8, ‘InitialStep’, 1e-4, ‘MaxStep’, 100);
[t, y] = ode15s(@fun_pde, t, IC, options, Nz, eps, n, Kf, k_f, u, rhop, dz);
% Define value
cc = y(:, 1:Nz);
qq = y(:, Nz+1:end);
% Recalculate new limit conditions
cc(:, 1) = 0;
cc(:, end) = cc(:, end-1);
% Plotting
cp = cc(:, end) ./ c0;
qp = qq(:, 🙂 ./ q0;
%q_promedio = mean(qq, 2); % Promedio de q en el lecho para cada instante de tiempo
%conversion = 1 – (q_promedio / q0); % Conversión normalizada
figure;
subplot(2, 1, 1);
time = t / 3600; % Convertir a horas
plot(time, 1- qp, ‘b’, ‘LineWidth’, 1.5);
xlabel(‘Tiempo (horas)’);
ylabel(‘Conversion’);
title(‘Curva de conversión durante la desorción’);
grid on;
subplot(2, 1, 2);
plot(t / 3600, (cc(:,:)), ‘LineWidth’, 1.5);
xlabel(‘Tiempo (horas)’);
ylabel(‘Soluciòn kg/m3’);
title(‘Curva de carga de la solucion durante la desorciòn’);
grid on;
% PDE function
function dydt = fun_pde(~, y, Nz, eps, n, Kf, k_f, u, rhop, dz)
dcdt = zeros(Nz, 1);
dqdt = zeros(Nz, 1);
c = y(1:Nz);
q = y(Nz+1:2*Nz);
% Boundary conditions
c(1) = max(c(1), 0); % Asegurar que c(1) sea no negativo
c(end) = c(end-1); % Asegurar que c(1) sea no negativo
% Interior nodes
qstar = zeros(Nz, 1);
dcdz = zeros(Nz, 1);
for i = 2:Nz-1
qstar(i) = Kf .* max(c(i), 1e-12).^(1/n); % Evitar problemas numéricos
dqdt(i) = k_f .* (qstar(i) – q(i));
% if i < Nz
dcdz(i) = (c(i+1) – c(i-1)) / (2 * dz);
%else
% dcdz(i) = (c(i) – c(i-1)) / dz;
%end
dcdt(i) = -u * dcdz(i) – rhop * ((1 – eps) / eps) .* dqdt(i);
end
dydt = [dcdt; dqdt];
end
next is a try to solve with finite diferences but get someting different:
L = 20 ; % Longitud del lecho (m)
eps = 0.4; % Porosidad
u = 0.2; % Velocidad superficial del fluido (m/s)
k_f = 0.02; % Constante de transferencia de masa (1/s)
c0 = 0;
Kf = 4; % Constante de Freundlich
rhop = 1520;
n = 2; % Exponente de Freundlich
% Concentración inicial del fluido (kg/m³)
q0 = 4.320; % Concentración inicial en el sólido (kg/m³)
% Densidad del adsorbente (kg/m³)
tf = 10; % Tiempo final de simulación (horas)
Nz = 100; % Número de nodos espaciales
% Discretización espacial y temporal
z = linspace(0, L, Nz);
t = linspace(0, tf*3600, Nt);
dz = z(2) – z(1);
dt = t(2) – t(1); % Paso temporal
% Condiciones iniciales
c = ones(Nt, Nz) * c0; % Concentración en el fluido
q = ones(Nt, Nz) * q0; % Concentración en el sólido
% Iteración en el tiempo (Diferencias Finitas Explícitas)
for ti = 1:Nt-1
for zi = 2:Nz-1
% Isoterma de Freundlich
qstar = Kf * max(c(ti, zi), 1e-12)^(1/n);
% Transferencia de masa (Desorción)
dqdt = k_f * (qstar – q(ti, zi));
% Gradiente espacial de concentración (Diferencias centradas)
dcdz = (c(ti, zi+1) – c(ti, zi-1)) / (2 * dz);
% Ecuación de balance de masa en el fluido
dcdt = -u * dcdz – rhop * ((1 – eps) / eps) * dqdt;
% Actualizar valores asegurando que sean positivos
c(ti+1, zi) = max(c(ti, zi) + dcdt * dt, 0);
q(ti+1, zi) = max(q(ti, zi) + dqdt * dt, 0);
end
end
% Condiciones de frontera
c(:, 1) = c0; % Entrada con concentración baja
c(:, Nz) = c(:, Nz-1); % Gradiente nulo en la salida
% Cálculo de la conversión normalizada
qp = q(:, 🙂 ./ q0;
% Graficar resultados
figure;
subplot(2, 1, 1);
plot(t / 3600, 1-qp, ‘b’, ‘LineWidth’, 1.5);
xlabel(‘Tiempo (horas)’);
ylabel(‘Conversion’);
title(‘Curva de conversión durante la desorción’);
grid on;
subplot(2, 1, 2);
c_salida = c(:, :); % Concentración en la salida del lecho
plot(t / 3600, c_salida, ‘r’, ‘LineWidth’, 1.5);
xlabel(‘Tiempo (horas)’);
ylabel(‘Soluciòn kg/m3’);
title(‘Curva de carga de la solucion durante la desorciòn’);
grid on;
I dont know why is wrong
Thanks in advance Hello , I want to transform this code that solves a pde equation with the ode solver into finite diferences, because I want to take the code as a matlab function block in simulink so it stands no ode solver(since it is an iterator take much time every time step so never ends simulation ) thats why i want to take it into finite differences .The equations are the following
The inital code is the following with ode solver:
L = 20 ; % Longitud del lecho (m)
eps = 0.4; % Porosidad
u = 0.2; % Velocidad superficial del fluido (m/s)
k_f = 0.02; % Constante de transferencia de masa (1/s)
c0 = 0;
Kf = 4; % Constante de Freundlich
rhop = 1520;
n = 2; % Exponente de Freundlich
% Concentración inicial del fluido (kg/m³)
q0 = 4.320; % Concentración inicial en el sólido (kg/m³)
% Densidad del adsorbente (kg/m³)
tf = 10; % Tiempo final de simulación (horas)
Nt = 100;
t = linspace(0, tf*3600, Nt);
Nz = 100;
z = linspace(0, L,Nz);
dz = z(2) – z(1);
% Initial conditions
ICA = max(ones(1, Nz) * c0, 1e-12); % Evitar valores negativos o cero
ICB = ones(1, Nz) * q0;
IC = [ICA ICB];
options = odeset(‘RelTol’, 1e-6, ‘AbsTol’, 1e-8, ‘InitialStep’, 1e-4, ‘MaxStep’, 100);
[t, y] = ode15s(@fun_pde, t, IC, options, Nz, eps, n, Kf, k_f, u, rhop, dz);
% Define value
cc = y(:, 1:Nz);
qq = y(:, Nz+1:end);
% Recalculate new limit conditions
cc(:, 1) = 0;
cc(:, end) = cc(:, end-1);
% Plotting
cp = cc(:, end) ./ c0;
qp = qq(:, 🙂 ./ q0;
%q_promedio = mean(qq, 2); % Promedio de q en el lecho para cada instante de tiempo
%conversion = 1 – (q_promedio / q0); % Conversión normalizada
figure;
subplot(2, 1, 1);
time = t / 3600; % Convertir a horas
plot(time, 1- qp, ‘b’, ‘LineWidth’, 1.5);
xlabel(‘Tiempo (horas)’);
ylabel(‘Conversion’);
title(‘Curva de conversión durante la desorción’);
grid on;
subplot(2, 1, 2);
plot(t / 3600, (cc(:,:)), ‘LineWidth’, 1.5);
xlabel(‘Tiempo (horas)’);
ylabel(‘Soluciòn kg/m3’);
title(‘Curva de carga de la solucion durante la desorciòn’);
grid on;
% PDE function
function dydt = fun_pde(~, y, Nz, eps, n, Kf, k_f, u, rhop, dz)
dcdt = zeros(Nz, 1);
dqdt = zeros(Nz, 1);
c = y(1:Nz);
q = y(Nz+1:2*Nz);
% Boundary conditions
c(1) = max(c(1), 0); % Asegurar que c(1) sea no negativo
c(end) = c(end-1); % Asegurar que c(1) sea no negativo
% Interior nodes
qstar = zeros(Nz, 1);
dcdz = zeros(Nz, 1);
for i = 2:Nz-1
qstar(i) = Kf .* max(c(i), 1e-12).^(1/n); % Evitar problemas numéricos
dqdt(i) = k_f .* (qstar(i) – q(i));
% if i < Nz
dcdz(i) = (c(i+1) – c(i-1)) / (2 * dz);
%else
% dcdz(i) = (c(i) – c(i-1)) / dz;
%end
dcdt(i) = -u * dcdz(i) – rhop * ((1 – eps) / eps) .* dqdt(i);
end
dydt = [dcdt; dqdt];
end
next is a try to solve with finite diferences but get someting different:
L = 20 ; % Longitud del lecho (m)
eps = 0.4; % Porosidad
u = 0.2; % Velocidad superficial del fluido (m/s)
k_f = 0.02; % Constante de transferencia de masa (1/s)
c0 = 0;
Kf = 4; % Constante de Freundlich
rhop = 1520;
n = 2; % Exponente de Freundlich
% Concentración inicial del fluido (kg/m³)
q0 = 4.320; % Concentración inicial en el sólido (kg/m³)
% Densidad del adsorbente (kg/m³)
tf = 10; % Tiempo final de simulación (horas)
Nz = 100; % Número de nodos espaciales
% Discretización espacial y temporal
z = linspace(0, L, Nz);
t = linspace(0, tf*3600, Nt);
dz = z(2) – z(1);
dt = t(2) – t(1); % Paso temporal
% Condiciones iniciales
c = ones(Nt, Nz) * c0; % Concentración en el fluido
q = ones(Nt, Nz) * q0; % Concentración en el sólido
% Iteración en el tiempo (Diferencias Finitas Explícitas)
for ti = 1:Nt-1
for zi = 2:Nz-1
% Isoterma de Freundlich
qstar = Kf * max(c(ti, zi), 1e-12)^(1/n);
% Transferencia de masa (Desorción)
dqdt = k_f * (qstar – q(ti, zi));
% Gradiente espacial de concentración (Diferencias centradas)
dcdz = (c(ti, zi+1) – c(ti, zi-1)) / (2 * dz);
% Ecuación de balance de masa en el fluido
dcdt = -u * dcdz – rhop * ((1 – eps) / eps) * dqdt;
% Actualizar valores asegurando que sean positivos
c(ti+1, zi) = max(c(ti, zi) + dcdt * dt, 0);
q(ti+1, zi) = max(q(ti, zi) + dqdt * dt, 0);
end
end
% Condiciones de frontera
c(:, 1) = c0; % Entrada con concentración baja
c(:, Nz) = c(:, Nz-1); % Gradiente nulo en la salida
% Cálculo de la conversión normalizada
qp = q(:, 🙂 ./ q0;
% Graficar resultados
figure;
subplot(2, 1, 1);
plot(t / 3600, 1-qp, ‘b’, ‘LineWidth’, 1.5);
xlabel(‘Tiempo (horas)’);
ylabel(‘Conversion’);
title(‘Curva de conversión durante la desorción’);
grid on;
subplot(2, 1, 2);
c_salida = c(:, :); % Concentración en la salida del lecho
plot(t / 3600, c_salida, ‘r’, ‘LineWidth’, 1.5);
xlabel(‘Tiempo (horas)’);
ylabel(‘Soluciòn kg/m3’);
title(‘Curva de carga de la solucion durante la desorciòn’);
grid on;
I dont know why is wrong
Thanks in advance pde, ode, matlab, solver, reactor MATLAB Answers — New Questions
open simulink project without opening all tabs
My Simulink project has previously been saved with too many open tabs.
The project will not now reopen because the PC runs out of memory trying to open all the previously open tabs (Matlab crashes)
How can I re-open my project without reopening all the tabs which were previously open when I saved the project?
Thanks.My Simulink project has previously been saved with too many open tabs.
The project will not now reopen because the PC runs out of memory trying to open all the previously open tabs (Matlab crashes)
How can I re-open my project without reopening all the tabs which were previously open when I saved the project?
Thanks. My Simulink project has previously been saved with too many open tabs.
The project will not now reopen because the PC runs out of memory trying to open all the previously open tabs (Matlab crashes)
How can I re-open my project without reopening all the tabs which were previously open when I saved the project?
Thanks. simulink tabs MATLAB Answers — New Questions
importlib.reload(matlab.engine) is not working
Hey,
I try to switch the python engine version in one single class. I added here a small example. Based on the used matlab version I want do add matlab.engine version dynamically. I tested many ways – importlib.reload(<matlabVersion>) is not working. What is the best way
import sys
import re
import importlib
matlab2017a ="d:CodeAreaModelQualityInterfacecoreToolsMatlabSimulinkmatlab17aPy35Libsite-packages"
matlab2016b ="d:CodeAreaModelQualityInterfacecoreToolsMatlabSimulinkmatlab16bPy35Libsite-packages"
sys.path.append(matlab2016b)
import matlab.engine
print(matlab.__file__)
print(matlab.engine.find_matlab())
def __RemoveMatlabEngineFromSysPath__(deliveredLibs):
for p in sys.path:
if p.find(deliveredLibs) != -1:
sys.path.remove(p)
__RemoveMatlabEngineFromSysPath__(matlab2016b)
sys.path.append(matlab2017a)
matlab = importlib.reload(matlab.engine)
print(matlab.engine.__file__)
print(matlab.engine.find_matlab())
Output:
File "d:/CodeArea/ModelQualityInterface/core/Tools/MatlabSimulink/test_multipleMatlabVersions.py", line 31, in <module>MatlabSimulink/test_multipleMatlabVersions.py", line
31, in <module> t__.py", line 166, in reload
matlab = importlib.reload(matlab.engine)
File "c:Program FilesPython35libimportlib__ini_exect__.py", line 166, in reload 697, in exec_module
_bootstrap._exec(spec, module) _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 626, in MatlabSimulinkmatlab16bPy35Libsite-packagesmatlabengine__init__.py", line 80, in <module>
_exec
File "<frozen importlib._bootstrap_external>", lineMatlabSimulinkmatlab16bPy35Libsite-packagesmatlabengineenginesession.py", line 8, in __init__ 697, in exec_module
File "<frozen importlib._bootstrap>", line 222, in not be initialized.
_call_with_frames_removed el__ of <matlab.engine.enginesession.EngineSession object at 0x00000212C1A2E7B8>>
File "d:CodeAreaModelQualityInterfacecoreToolsMatlabSimulinkmatlab16bPy35Libsite-packagesmatlabMatlabSimulinkmatlab16bPy35Libsite-packagesmatlabengineenginesession.py", line 14, in __del__engine__init__.py", line 80, in <module>
_session = EngineSession() MatlabSimulinkmatlab16bPy35Libsite-packagesmatlabengineenginesession.py", line 17, in release
File "d:CodeAreaModelQualityInterfacecoreToolsMatlabSimulinkmatlab16bPy35Libsite-packagesmatlabengineenginesession.py", line 8, in __init__
pythonengine.createProcess()
matlab.engine.EngineError: MATLAB process session cannot be initialized.
Exception ignored in: <bound method EngineSession.__del__ of <matlab.engine.enginesession.EngineSession object at 0x00000212C1A2E7B8>>
Traceback (most recent call last):
File "d:CodeAreaModelQualityInterfacecoreToolsMatlabSimulinkmatlab16bPy35Libsite-packagesmatlabengineenginesession.py", line 14, in __del__
self.release()
File "d:CodeAreaModelQualityInterfacecoreToolsMatlabSimulinkmatlab16bPy35Libsite-packagesmatlabengineenginesession.py", line 17, in release
if self._process_created:
AttributeError: ‘EngineSession’ object has no attribute ‘_process_created’Hey,
I try to switch the python engine version in one single class. I added here a small example. Based on the used matlab version I want do add matlab.engine version dynamically. I tested many ways – importlib.reload(<matlabVersion>) is not working. What is the best way
import sys
import re
import importlib
matlab2017a ="d:CodeAreaModelQualityInterfacecoreToolsMatlabSimulinkmatlab17aPy35Libsite-packages"
matlab2016b ="d:CodeAreaModelQualityInterfacecoreToolsMatlabSimulinkmatlab16bPy35Libsite-packages"
sys.path.append(matlab2016b)
import matlab.engine
print(matlab.__file__)
print(matlab.engine.find_matlab())
def __RemoveMatlabEngineFromSysPath__(deliveredLibs):
for p in sys.path:
if p.find(deliveredLibs) != -1:
sys.path.remove(p)
__RemoveMatlabEngineFromSysPath__(matlab2016b)
sys.path.append(matlab2017a)
matlab = importlib.reload(matlab.engine)
print(matlab.engine.__file__)
print(matlab.engine.find_matlab())
Output:
File "d:/CodeArea/ModelQualityInterface/core/Tools/MatlabSimulink/test_multipleMatlabVersions.py", line 31, in <module>MatlabSimulink/test_multipleMatlabVersions.py", line
31, in <module> t__.py", line 166, in reload
matlab = importlib.reload(matlab.engine)
File "c:Program FilesPython35libimportlib__ini_exect__.py", line 166, in reload 697, in exec_module
_bootstrap._exec(spec, module) _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 626, in MatlabSimulinkmatlab16bPy35Libsite-packagesmatlabengine__init__.py", line 80, in <module>
_exec
File "<frozen importlib._bootstrap_external>", lineMatlabSimulinkmatlab16bPy35Libsite-packagesmatlabengineenginesession.py", line 8, in __init__ 697, in exec_module
File "<frozen importlib._bootstrap>", line 222, in not be initialized.
_call_with_frames_removed el__ of <matlab.engine.enginesession.EngineSession object at 0x00000212C1A2E7B8>>
File "d:CodeAreaModelQualityInterfacecoreToolsMatlabSimulinkmatlab16bPy35Libsite-packagesmatlabMatlabSimulinkmatlab16bPy35Libsite-packagesmatlabengineenginesession.py", line 14, in __del__engine__init__.py", line 80, in <module>
_session = EngineSession() MatlabSimulinkmatlab16bPy35Libsite-packagesmatlabengineenginesession.py", line 17, in release
File "d:CodeAreaModelQualityInterfacecoreToolsMatlabSimulinkmatlab16bPy35Libsite-packagesmatlabengineenginesession.py", line 8, in __init__
pythonengine.createProcess()
matlab.engine.EngineError: MATLAB process session cannot be initialized.
Exception ignored in: <bound method EngineSession.__del__ of <matlab.engine.enginesession.EngineSession object at 0x00000212C1A2E7B8>>
Traceback (most recent call last):
File "d:CodeAreaModelQualityInterfacecoreToolsMatlabSimulinkmatlab16bPy35Libsite-packagesmatlabengineenginesession.py", line 14, in __del__
self.release()
File "d:CodeAreaModelQualityInterfacecoreToolsMatlabSimulinkmatlab16bPy35Libsite-packagesmatlabengineenginesession.py", line 17, in release
if self._process_created:
AttributeError: ‘EngineSession’ object has no attribute ‘_process_created’ Hey,
I try to switch the python engine version in one single class. I added here a small example. Based on the used matlab version I want do add matlab.engine version dynamically. I tested many ways – importlib.reload(<matlabVersion>) is not working. What is the best way
import sys
import re
import importlib
matlab2017a ="d:CodeAreaModelQualityInterfacecoreToolsMatlabSimulinkmatlab17aPy35Libsite-packages"
matlab2016b ="d:CodeAreaModelQualityInterfacecoreToolsMatlabSimulinkmatlab16bPy35Libsite-packages"
sys.path.append(matlab2016b)
import matlab.engine
print(matlab.__file__)
print(matlab.engine.find_matlab())
def __RemoveMatlabEngineFromSysPath__(deliveredLibs):
for p in sys.path:
if p.find(deliveredLibs) != -1:
sys.path.remove(p)
__RemoveMatlabEngineFromSysPath__(matlab2016b)
sys.path.append(matlab2017a)
matlab = importlib.reload(matlab.engine)
print(matlab.engine.__file__)
print(matlab.engine.find_matlab())
Output:
File "d:/CodeArea/ModelQualityInterface/core/Tools/MatlabSimulink/test_multipleMatlabVersions.py", line 31, in <module>MatlabSimulink/test_multipleMatlabVersions.py", line
31, in <module> t__.py", line 166, in reload
matlab = importlib.reload(matlab.engine)
File "c:Program FilesPython35libimportlib__ini_exect__.py", line 166, in reload 697, in exec_module
_bootstrap._exec(spec, module) _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 626, in MatlabSimulinkmatlab16bPy35Libsite-packagesmatlabengine__init__.py", line 80, in <module>
_exec
File "<frozen importlib._bootstrap_external>", lineMatlabSimulinkmatlab16bPy35Libsite-packagesmatlabengineenginesession.py", line 8, in __init__ 697, in exec_module
File "<frozen importlib._bootstrap>", line 222, in not be initialized.
_call_with_frames_removed el__ of <matlab.engine.enginesession.EngineSession object at 0x00000212C1A2E7B8>>
File "d:CodeAreaModelQualityInterfacecoreToolsMatlabSimulinkmatlab16bPy35Libsite-packagesmatlabMatlabSimulinkmatlab16bPy35Libsite-packagesmatlabengineenginesession.py", line 14, in __del__engine__init__.py", line 80, in <module>
_session = EngineSession() MatlabSimulinkmatlab16bPy35Libsite-packagesmatlabengineenginesession.py", line 17, in release
File "d:CodeAreaModelQualityInterfacecoreToolsMatlabSimulinkmatlab16bPy35Libsite-packagesmatlabengineenginesession.py", line 8, in __init__
pythonengine.createProcess()
matlab.engine.EngineError: MATLAB process session cannot be initialized.
Exception ignored in: <bound method EngineSession.__del__ of <matlab.engine.enginesession.EngineSession object at 0x00000212C1A2E7B8>>
Traceback (most recent call last):
File "d:CodeAreaModelQualityInterfacecoreToolsMatlabSimulinkmatlab16bPy35Libsite-packagesmatlabengineenginesession.py", line 14, in __del__
self.release()
File "d:CodeAreaModelQualityInterfacecoreToolsMatlabSimulinkmatlab16bPy35Libsite-packagesmatlabengineenginesession.py", line 17, in release
if self._process_created:
AttributeError: ‘EngineSession’ object has no attribute ‘_process_created’ python, import MATLAB Answers — New Questions
Select data values from within a range
So I have a matrix of about 42000 rows, which give latitudes and longitudes of each entry in columns 7 and 8 respectively. Right now, my script pulls latitudes and longitudes as variables, and then another couple lines select values within a range. My script is below:
lat_r = A(:,7);
long_r = A(:,8);
lat = lat_r(lat_r > x & lat_r < y);
long = long_r(long_r > a & long_r < b);
My problem is that this only lists each value from each individual column that is between the given values (x,y or a,b). What I’d like to do is be able to find which rows have a latitude within the given range and then check if the corresponding longitude is also within the given range, then enter these values into a nx2 matrix.
This is probably a quick answer, but I’m fairly new working with MATLAB so any help would be greatly appreciated.So I have a matrix of about 42000 rows, which give latitudes and longitudes of each entry in columns 7 and 8 respectively. Right now, my script pulls latitudes and longitudes as variables, and then another couple lines select values within a range. My script is below:
lat_r = A(:,7);
long_r = A(:,8);
lat = lat_r(lat_r > x & lat_r < y);
long = long_r(long_r > a & long_r < b);
My problem is that this only lists each value from each individual column that is between the given values (x,y or a,b). What I’d like to do is be able to find which rows have a latitude within the given range and then check if the corresponding longitude is also within the given range, then enter these values into a nx2 matrix.
This is probably a quick answer, but I’m fairly new working with MATLAB so any help would be greatly appreciated. So I have a matrix of about 42000 rows, which give latitudes and longitudes of each entry in columns 7 and 8 respectively. Right now, my script pulls latitudes and longitudes as variables, and then another couple lines select values within a range. My script is below:
lat_r = A(:,7);
long_r = A(:,8);
lat = lat_r(lat_r > x & lat_r < y);
long = long_r(long_r > a & long_r < b);
My problem is that this only lists each value from each individual column that is between the given values (x,y or a,b). What I’d like to do is be able to find which rows have a latitude within the given range and then check if the corresponding longitude is also within the given range, then enter these values into a nx2 matrix.
This is probably a quick answer, but I’m fairly new working with MATLAB so any help would be greatly appreciated. matrix, array, range MATLAB Answers — New Questions
Editability of Files Packaged into MATLAB Toolbox File (mltbx file)
I need to deliver a MATLAB Toolbox File (extension .mltbx) for a customer. All the files have read / write / execute permissions (including the GettingStarted.mlx file) after the customer installs the mltbx file.
I want the files to be read only in order to protect the install from mistakes that the end user may make. It appears that even when I set the permissions to be read-only just prior to packaging up the .mltbx, the end result is that the files have read / write permissions.
How can I fix this?
Thanks.I need to deliver a MATLAB Toolbox File (extension .mltbx) for a customer. All the files have read / write / execute permissions (including the GettingStarted.mlx file) after the customer installs the mltbx file.
I want the files to be read only in order to protect the install from mistakes that the end user may make. It appears that even when I set the permissions to be read-only just prior to packaging up the .mltbx, the end result is that the files have read / write permissions.
How can I fix this?
Thanks. I need to deliver a MATLAB Toolbox File (extension .mltbx) for a customer. All the files have read / write / execute permissions (including the GettingStarted.mlx file) after the customer installs the mltbx file.
I want the files to be read only in order to protect the install from mistakes that the end user may make. It appears that even when I set the permissions to be read-only just prior to packaging up the .mltbx, the end result is that the files have read / write permissions.
How can I fix this?
Thanks. matlab, matlab toolbox file, .mltbx, file permissions MATLAB Answers — New Questions
Create multiple subtables from multiple .tsv tables
I have 120 .tsv files (see example example in "sub-m0001_file.tsv"). The path is the same for all the files except in the 9th folder. See the paths for the first two .tsv files below:
/f1/f2/f3/f4/f5/f6/f7/f8/sub-m0001/f10/f11/sub-m0001_file.tsv
/f1/f2/f3/f4/f5/f6/f7/f8/sub-m0002/f10/f11/sub-m0002_file.tsv
How can I get subtables (i.e., 1 table per file) including only the following six columns: ‘trans_x’, ‘trans_y’, ‘trans_z’, ‘rot_x’, ‘rot_y’, ‘rot_z’?
The following code does it only for the first .tsv file. Any hint to go recursively over the 120 .tsv files?
mat = dir(‘/f1/f2/f3/f4/f5/f6/f7/f8/sub-m*/f10/f11/*file.tsv’);
for files_i = 1:length(mat)
data = fullfile(mat(files_i).name);
x = readtable(data,"FileType","text",’Delimiter’, ‘t’);
vars = {‘trans_x’ ‘trans_y’ ‘trans_z’ ‘rot_x’ ‘rot_y’ ‘rot_z’};
new_x = x(:,vars);
end
Then, I need to store each file in a folder which filename corresponds to sub-m*. for instance (example sub-m0001_subfile.txt) see:
/new/path/sub-m0001/sub-m0001_subfile.txt
/new/path/sub-m0002/sub-m0002_subfile.txt
Many thanks in advanceI have 120 .tsv files (see example example in "sub-m0001_file.tsv"). The path is the same for all the files except in the 9th folder. See the paths for the first two .tsv files below:
/f1/f2/f3/f4/f5/f6/f7/f8/sub-m0001/f10/f11/sub-m0001_file.tsv
/f1/f2/f3/f4/f5/f6/f7/f8/sub-m0002/f10/f11/sub-m0002_file.tsv
How can I get subtables (i.e., 1 table per file) including only the following six columns: ‘trans_x’, ‘trans_y’, ‘trans_z’, ‘rot_x’, ‘rot_y’, ‘rot_z’?
The following code does it only for the first .tsv file. Any hint to go recursively over the 120 .tsv files?
mat = dir(‘/f1/f2/f3/f4/f5/f6/f7/f8/sub-m*/f10/f11/*file.tsv’);
for files_i = 1:length(mat)
data = fullfile(mat(files_i).name);
x = readtable(data,"FileType","text",’Delimiter’, ‘t’);
vars = {‘trans_x’ ‘trans_y’ ‘trans_z’ ‘rot_x’ ‘rot_y’ ‘rot_z’};
new_x = x(:,vars);
end
Then, I need to store each file in a folder which filename corresponds to sub-m*. for instance (example sub-m0001_subfile.txt) see:
/new/path/sub-m0001/sub-m0001_subfile.txt
/new/path/sub-m0002/sub-m0002_subfile.txt
Many thanks in advance I have 120 .tsv files (see example example in "sub-m0001_file.tsv"). The path is the same for all the files except in the 9th folder. See the paths for the first two .tsv files below:
/f1/f2/f3/f4/f5/f6/f7/f8/sub-m0001/f10/f11/sub-m0001_file.tsv
/f1/f2/f3/f4/f5/f6/f7/f8/sub-m0002/f10/f11/sub-m0002_file.tsv
How can I get subtables (i.e., 1 table per file) including only the following six columns: ‘trans_x’, ‘trans_y’, ‘trans_z’, ‘rot_x’, ‘rot_y’, ‘rot_z’?
The following code does it only for the first .tsv file. Any hint to go recursively over the 120 .tsv files?
mat = dir(‘/f1/f2/f3/f4/f5/f6/f7/f8/sub-m*/f10/f11/*file.tsv’);
for files_i = 1:length(mat)
data = fullfile(mat(files_i).name);
x = readtable(data,"FileType","text",’Delimiter’, ‘t’);
vars = {‘trans_x’ ‘trans_y’ ‘trans_z’ ‘rot_x’ ‘rot_y’ ‘rot_z’};
new_x = x(:,vars);
end
Then, I need to store each file in a folder which filename corresponds to sub-m*. for instance (example sub-m0001_subfile.txt) see:
/new/path/sub-m0001/sub-m0001_subfile.txt
/new/path/sub-m0002/sub-m0002_subfile.txt
Many thanks in advance readtable, .tsv MATLAB Answers — New Questions
rect function on the interval x= -5:0.1:5.
x=-5*pi:0.1:5*pi;
y=(pi/2)*sinc(x/2);
plot(x,y)
title(‘s𝑖𝑛((𝜋/2)𝑥)/𝑥 plot’)
xlabel(‘x’);
ylabel(‘sin((𝜋/2)x)/x’)
grid on;
would this be correct when plotting Rect function using rectangularPulse on the interval x= -5:0.1:5?x=-5*pi:0.1:5*pi;
y=(pi/2)*sinc(x/2);
plot(x,y)
title(‘s𝑖𝑛((𝜋/2)𝑥)/𝑥 plot’)
xlabel(‘x’);
ylabel(‘sin((𝜋/2)x)/x’)
grid on;
would this be correct when plotting Rect function using rectangularPulse on the interval x= -5:0.1:5? x=-5*pi:0.1:5*pi;
y=(pi/2)*sinc(x/2);
plot(x,y)
title(‘s𝑖𝑛((𝜋/2)𝑥)/𝑥 plot’)
xlabel(‘x’);
ylabel(‘sin((𝜋/2)x)/x’)
grid on;
would this be correct when plotting Rect function using rectangularPulse on the interval x= -5:0.1:5? rectangularpulse MATLAB Answers — New Questions
How I can plot surface countour plot and velocity plot on same garph using MATLAB
How I can plot surface countour plot and velocity plot on same garph using MATLABHow I can plot surface countour plot and velocity plot on same garph using MATLAB How I can plot surface countour plot and velocity plot on same garph using MATLAB simulation MATLAB Answers — New Questions
plot graph with cylinder
Is it possible to plot a 3d graph by using a cylinders (or a tubes) instead of the default straight lines in Matlab?Is it possible to plot a 3d graph by using a cylinders (or a tubes) instead of the default straight lines in Matlab? Is it possible to plot a 3d graph by using a cylinders (or a tubes) instead of the default straight lines in Matlab? graph MATLAB Answers — New Questions
How to export my workspace variables and bus structure to a csv file?
I would like to export / save the structure of my workspace busses in .csv or other delimited format (for spreadsheet manipulation). Essentially, I would like to save all of my busses, and their parameters, in something like the "Type Editor" view which appears when I double-click a bus in my workspace. (At this point, the parameter values aren’t as important as the bus structure itself).
What is the best way to approach this?I would like to export / save the structure of my workspace busses in .csv or other delimited format (for spreadsheet manipulation). Essentially, I would like to save all of my busses, and their parameters, in something like the "Type Editor" view which appears when I double-click a bus in my workspace. (At this point, the parameter values aren’t as important as the bus structure itself).
What is the best way to approach this? I would like to export / save the structure of my workspace busses in .csv or other delimited format (for spreadsheet manipulation). Essentially, I would like to save all of my busses, and their parameters, in something like the "Type Editor" view which appears when I double-click a bus in my workspace. (At this point, the parameter values aren’t as important as the bus structure itself).
What is the best way to approach this? bus structure, export type editor view, comma delimited, workspace MATLAB Answers — New Questions
Convert Set of (x,y) Coordinates Into Polygon
I converted the attached coordinates (x,y) into an alphashape. See image.
shp = alphaShape(coordinates(:,1),coordinates(:,2),’HoleThreshold’,50);
What I need are the coordinates at the polygon vertices (shown in red), and importantly, in the proper order shown with the numbers. I would like to be able to use the polyshape function next…
I have toyed with boundaryfacet, delauney but with no luck.
Any suggestions?
Thanks.I converted the attached coordinates (x,y) into an alphashape. See image.
shp = alphaShape(coordinates(:,1),coordinates(:,2),’HoleThreshold’,50);
What I need are the coordinates at the polygon vertices (shown in red), and importantly, in the proper order shown with the numbers. I would like to be able to use the polyshape function next…
I have toyed with boundaryfacet, delauney but with no luck.
Any suggestions?
Thanks. I converted the attached coordinates (x,y) into an alphashape. See image.
shp = alphaShape(coordinates(:,1),coordinates(:,2),’HoleThreshold’,50);
What I need are the coordinates at the polygon vertices (shown in red), and importantly, in the proper order shown with the numbers. I would like to be able to use the polyshape function next…
I have toyed with boundaryfacet, delauney but with no luck.
Any suggestions?
Thanks. alphashape, polyshape, boundary MATLAB Answers — New Questions
Using msiwrite with phased antenna objects
I’m able to plot the radiation pattern from a phased antenna array object; how do I write this to a file using the msiwrite function?
msiwrite seems to accept inputs from other antenna types (e.g. helix), but all the data should be available within the phased.ShortDipoleAntennaElement object to be able to be used by the msiwrite function. What am I missing?
fc = 500e6;
antenna = phased.ShortDipoleAntennaElement(…
‘FrequencyRange’,[50e6,1000e6],…
‘AxisDirection’,’Z’);
array = phased.UCA(‘NumElements’,11,’Radius’,1.5,’Element’,antenna);
msiwrite(antenna,fc,’UCA_File’);I’m able to plot the radiation pattern from a phased antenna array object; how do I write this to a file using the msiwrite function?
msiwrite seems to accept inputs from other antenna types (e.g. helix), but all the data should be available within the phased.ShortDipoleAntennaElement object to be able to be used by the msiwrite function. What am I missing?
fc = 500e6;
antenna = phased.ShortDipoleAntennaElement(…
‘FrequencyRange’,[50e6,1000e6],…
‘AxisDirection’,’Z’);
array = phased.UCA(‘NumElements’,11,’Radius’,1.5,’Element’,antenna);
msiwrite(antenna,fc,’UCA_File’); I’m able to plot the radiation pattern from a phased antenna array object; how do I write this to a file using the msiwrite function?
msiwrite seems to accept inputs from other antenna types (e.g. helix), but all the data should be available within the phased.ShortDipoleAntennaElement object to be able to be used by the msiwrite function. What am I missing?
fc = 500e6;
antenna = phased.ShortDipoleAntennaElement(…
‘FrequencyRange’,[50e6,1000e6],…
‘AxisDirection’,’Z’);
array = phased.UCA(‘NumElements’,11,’Radius’,1.5,’Element’,antenna);
msiwrite(antenna,fc,’UCA_File’); antenna MATLAB Answers — New Questions
Trying to obtain coefficient matrix of Bspline matrix then obtaining its quasi-diagonal matrix ?
I tried to obtain the coefficients of B-spline matrix using the following code :
function C_matrix = calculateBsplineCoefficientMatrix(s)
% Number of input samples
N = length(s);
% Construct Alpha Values (Used in the Recursive Calculation)
alpha_values = zeros(1, 10);
alpha_values(1) = -1/4;
for i = 2:10
alpha_values(i) = -1 / (4 + alpha_values(i – 1));
end
alpha = alpha_values(end);
b_i = -alpha / (1 – alpha^2);
% Construct Forward Recursion Matrix (C_plus)
C_plus = zeros(N, N); % Matrix to store forward recursion values
C_plus(:, 1) = 1; % Initialize first column as 1
for k = 2:N
C_plus(k, 🙂 = alpha * C_plus(k-1, :);
C_plus(k, k) = 1; % Set diagonal values to 1 for recursion steps
end
% Construct Backward Recursion Matrix (C_minus)
C_minus = zeros(N, N);
I_N = eye(N); % Identity matrix of size NxN
C_minus(N, 🙂 = b_i * (2 * C_plus(N, 🙂 – I_N(N, :));
for k = N-1:-1:1
C_minus(k, 🙂 = alpha * (C_minus(k+1, 🙂 – C_plus(k, :));
end
% Construct Final B-spline Coefficient Matrix
C_matrix = 6 * C_minus;
end
s here represents the signal or sequence basically this code is created from the paper FastO-line interpolation by Dooley in pdf document(1).
s = rand(1, 4);
C_spline_matrix = calculateBsplineCoefficientMatrix(s);
disp(‘B-Spline Coefficients Matrix Form:’);
disp(C_spline_matrix);
The Solution is B-Spline Coefficients Matrix Form:
B-Spline Coefficients Matrix Form:
1.7327 -0.4665 0.1333 -0.0333
-0.4665 1.7410 -0.4974 0.1244
0.1333 -0.4974 1.8564 -0.4641
-0.0666 0.2487 -0.9282 1.7321
Then I tried to calculate its quasi diagonal matrix using the following code :
M = length(s); % Polynomial order or interpolation order
% Compute Transformation Matrices
T_mu = compute_TD(M); % Transformation matrix T_mu
T_z = calculate_Tz(M); % Transformation matrix T_z
% Ensure numerical stability
T_mu_invT = inv(transpose(T_mu)); % Explicit inverse transpose of T_mu
T_z_inv = inv(T_z); % Explicit inverse of T_z
% Compute the quasi-diagonal matrix C_LCN
C_LCN = T_mu_invT .*C_spline_matrix .* T_z_inv;
% Display the final quasi-diagonal matrix
disp(‘Computed C_LCN Matrix:’);
disp(C_LCN);
The solution of quasi diagonal matrix
Computed C_LCN Matrix:
1.8384 0 0 0
-0.5937 -2.4397 0 0
0.1728 1.1772 0.8176 0
-0.0168 -0.2263 -0.3135 -0.0388
The relevant functions are given below:
function Td1 = compute_Td1(M)
% Create a matrix of binomial coefficients
[I, J] = ndgrid(1:M, 1:M);
binomials = zeros(M, M);
for ii = 1:M
for jj = 1:M
if jj <= ii
binomials(ii, jj) = nchoosek(ii-1, jj-1);
end
end
end
% Compute powers and combine with binomial coefficients
powers = ((- (M – 1) / 2) .^ (I – J)) .* (J <= I);
Td1 = binomials .* powers;
% Debugging: Display Td1 matrix
disp(‘Td1 Matrix:’);
disp(Td1);
end
function Td2 = compute_Td2(M)
% Compute the Td2 matrix
Td2 = eye(M+1);
for n = 2:M+1
for k = 2:n-1
Td2(n, k) = Td2(n-1, k-1) – (n-2) * Td2(n-1, k);
end
end
Td2 = Td2(2:M+1, 2:M+1);
% Debugging: Display Td2 matrix
disp(‘Td2 Matrix:’);
disp(Td2);
end
function TD = compute_TD(M)
Td1 = compute_Td1(M);
Td2 = compute_Td2(M);
% Compute TD
TD = Td1 * Td2;
% Force symmetry in TD
TD = (TD + TD’) / 2;
% Regularization for numerical stability
TD = TD + 1e-8 * eye(size(TD));
% Debugging: Display TD matrix
disp(‘Symmetrized TD Matrix:’);
disp(TD);
end
function Tz = calculate_Tz(M)
% Generate the Tz transformation matrix for Newton interpolation
Tz = zeros(M, M);
for i = 1:M
for j = 1:i
Tz(i, j) = nchoosek(i-1, j-1) * (-1)^(j+1);
end
end
% Regularization for numerical stability
Tz = Tz + 1e-8 * eye(size(Tz));
% Debugging: Display Tz matrix
disp(‘Tz Matrix:’);
disp(Tz);
end
The problem is the it does not match the values as solved in the paper Electronic letters…
The solutions provided are :
Please could any body help me correcting this code to obtain the solution ?I tried to obtain the coefficients of B-spline matrix using the following code :
function C_matrix = calculateBsplineCoefficientMatrix(s)
% Number of input samples
N = length(s);
% Construct Alpha Values (Used in the Recursive Calculation)
alpha_values = zeros(1, 10);
alpha_values(1) = -1/4;
for i = 2:10
alpha_values(i) = -1 / (4 + alpha_values(i – 1));
end
alpha = alpha_values(end);
b_i = -alpha / (1 – alpha^2);
% Construct Forward Recursion Matrix (C_plus)
C_plus = zeros(N, N); % Matrix to store forward recursion values
C_plus(:, 1) = 1; % Initialize first column as 1
for k = 2:N
C_plus(k, 🙂 = alpha * C_plus(k-1, :);
C_plus(k, k) = 1; % Set diagonal values to 1 for recursion steps
end
% Construct Backward Recursion Matrix (C_minus)
C_minus = zeros(N, N);
I_N = eye(N); % Identity matrix of size NxN
C_minus(N, 🙂 = b_i * (2 * C_plus(N, 🙂 – I_N(N, :));
for k = N-1:-1:1
C_minus(k, 🙂 = alpha * (C_minus(k+1, 🙂 – C_plus(k, :));
end
% Construct Final B-spline Coefficient Matrix
C_matrix = 6 * C_minus;
end
s here represents the signal or sequence basically this code is created from the paper FastO-line interpolation by Dooley in pdf document(1).
s = rand(1, 4);
C_spline_matrix = calculateBsplineCoefficientMatrix(s);
disp(‘B-Spline Coefficients Matrix Form:’);
disp(C_spline_matrix);
The Solution is B-Spline Coefficients Matrix Form:
B-Spline Coefficients Matrix Form:
1.7327 -0.4665 0.1333 -0.0333
-0.4665 1.7410 -0.4974 0.1244
0.1333 -0.4974 1.8564 -0.4641
-0.0666 0.2487 -0.9282 1.7321
Then I tried to calculate its quasi diagonal matrix using the following code :
M = length(s); % Polynomial order or interpolation order
% Compute Transformation Matrices
T_mu = compute_TD(M); % Transformation matrix T_mu
T_z = calculate_Tz(M); % Transformation matrix T_z
% Ensure numerical stability
T_mu_invT = inv(transpose(T_mu)); % Explicit inverse transpose of T_mu
T_z_inv = inv(T_z); % Explicit inverse of T_z
% Compute the quasi-diagonal matrix C_LCN
C_LCN = T_mu_invT .*C_spline_matrix .* T_z_inv;
% Display the final quasi-diagonal matrix
disp(‘Computed C_LCN Matrix:’);
disp(C_LCN);
The solution of quasi diagonal matrix
Computed C_LCN Matrix:
1.8384 0 0 0
-0.5937 -2.4397 0 0
0.1728 1.1772 0.8176 0
-0.0168 -0.2263 -0.3135 -0.0388
The relevant functions are given below:
function Td1 = compute_Td1(M)
% Create a matrix of binomial coefficients
[I, J] = ndgrid(1:M, 1:M);
binomials = zeros(M, M);
for ii = 1:M
for jj = 1:M
if jj <= ii
binomials(ii, jj) = nchoosek(ii-1, jj-1);
end
end
end
% Compute powers and combine with binomial coefficients
powers = ((- (M – 1) / 2) .^ (I – J)) .* (J <= I);
Td1 = binomials .* powers;
% Debugging: Display Td1 matrix
disp(‘Td1 Matrix:’);
disp(Td1);
end
function Td2 = compute_Td2(M)
% Compute the Td2 matrix
Td2 = eye(M+1);
for n = 2:M+1
for k = 2:n-1
Td2(n, k) = Td2(n-1, k-1) – (n-2) * Td2(n-1, k);
end
end
Td2 = Td2(2:M+1, 2:M+1);
% Debugging: Display Td2 matrix
disp(‘Td2 Matrix:’);
disp(Td2);
end
function TD = compute_TD(M)
Td1 = compute_Td1(M);
Td2 = compute_Td2(M);
% Compute TD
TD = Td1 * Td2;
% Force symmetry in TD
TD = (TD + TD’) / 2;
% Regularization for numerical stability
TD = TD + 1e-8 * eye(size(TD));
% Debugging: Display TD matrix
disp(‘Symmetrized TD Matrix:’);
disp(TD);
end
function Tz = calculate_Tz(M)
% Generate the Tz transformation matrix for Newton interpolation
Tz = zeros(M, M);
for i = 1:M
for j = 1:i
Tz(i, j) = nchoosek(i-1, j-1) * (-1)^(j+1);
end
end
% Regularization for numerical stability
Tz = Tz + 1e-8 * eye(size(Tz));
% Debugging: Display Tz matrix
disp(‘Tz Matrix:’);
disp(Tz);
end
The problem is the it does not match the values as solved in the paper Electronic letters…
The solutions provided are :
Please could any body help me correcting this code to obtain the solution ? I tried to obtain the coefficients of B-spline matrix using the following code :
function C_matrix = calculateBsplineCoefficientMatrix(s)
% Number of input samples
N = length(s);
% Construct Alpha Values (Used in the Recursive Calculation)
alpha_values = zeros(1, 10);
alpha_values(1) = -1/4;
for i = 2:10
alpha_values(i) = -1 / (4 + alpha_values(i – 1));
end
alpha = alpha_values(end);
b_i = -alpha / (1 – alpha^2);
% Construct Forward Recursion Matrix (C_plus)
C_plus = zeros(N, N); % Matrix to store forward recursion values
C_plus(:, 1) = 1; % Initialize first column as 1
for k = 2:N
C_plus(k, 🙂 = alpha * C_plus(k-1, :);
C_plus(k, k) = 1; % Set diagonal values to 1 for recursion steps
end
% Construct Backward Recursion Matrix (C_minus)
C_minus = zeros(N, N);
I_N = eye(N); % Identity matrix of size NxN
C_minus(N, 🙂 = b_i * (2 * C_plus(N, 🙂 – I_N(N, :));
for k = N-1:-1:1
C_minus(k, 🙂 = alpha * (C_minus(k+1, 🙂 – C_plus(k, :));
end
% Construct Final B-spline Coefficient Matrix
C_matrix = 6 * C_minus;
end
s here represents the signal or sequence basically this code is created from the paper FastO-line interpolation by Dooley in pdf document(1).
s = rand(1, 4);
C_spline_matrix = calculateBsplineCoefficientMatrix(s);
disp(‘B-Spline Coefficients Matrix Form:’);
disp(C_spline_matrix);
The Solution is B-Spline Coefficients Matrix Form:
B-Spline Coefficients Matrix Form:
1.7327 -0.4665 0.1333 -0.0333
-0.4665 1.7410 -0.4974 0.1244
0.1333 -0.4974 1.8564 -0.4641
-0.0666 0.2487 -0.9282 1.7321
Then I tried to calculate its quasi diagonal matrix using the following code :
M = length(s); % Polynomial order or interpolation order
% Compute Transformation Matrices
T_mu = compute_TD(M); % Transformation matrix T_mu
T_z = calculate_Tz(M); % Transformation matrix T_z
% Ensure numerical stability
T_mu_invT = inv(transpose(T_mu)); % Explicit inverse transpose of T_mu
T_z_inv = inv(T_z); % Explicit inverse of T_z
% Compute the quasi-diagonal matrix C_LCN
C_LCN = T_mu_invT .*C_spline_matrix .* T_z_inv;
% Display the final quasi-diagonal matrix
disp(‘Computed C_LCN Matrix:’);
disp(C_LCN);
The solution of quasi diagonal matrix
Computed C_LCN Matrix:
1.8384 0 0 0
-0.5937 -2.4397 0 0
0.1728 1.1772 0.8176 0
-0.0168 -0.2263 -0.3135 -0.0388
The relevant functions are given below:
function Td1 = compute_Td1(M)
% Create a matrix of binomial coefficients
[I, J] = ndgrid(1:M, 1:M);
binomials = zeros(M, M);
for ii = 1:M
for jj = 1:M
if jj <= ii
binomials(ii, jj) = nchoosek(ii-1, jj-1);
end
end
end
% Compute powers and combine with binomial coefficients
powers = ((- (M – 1) / 2) .^ (I – J)) .* (J <= I);
Td1 = binomials .* powers;
% Debugging: Display Td1 matrix
disp(‘Td1 Matrix:’);
disp(Td1);
end
function Td2 = compute_Td2(M)
% Compute the Td2 matrix
Td2 = eye(M+1);
for n = 2:M+1
for k = 2:n-1
Td2(n, k) = Td2(n-1, k-1) – (n-2) * Td2(n-1, k);
end
end
Td2 = Td2(2:M+1, 2:M+1);
% Debugging: Display Td2 matrix
disp(‘Td2 Matrix:’);
disp(Td2);
end
function TD = compute_TD(M)
Td1 = compute_Td1(M);
Td2 = compute_Td2(M);
% Compute TD
TD = Td1 * Td2;
% Force symmetry in TD
TD = (TD + TD’) / 2;
% Regularization for numerical stability
TD = TD + 1e-8 * eye(size(TD));
% Debugging: Display TD matrix
disp(‘Symmetrized TD Matrix:’);
disp(TD);
end
function Tz = calculate_Tz(M)
% Generate the Tz transformation matrix for Newton interpolation
Tz = zeros(M, M);
for i = 1:M
for j = 1:i
Tz(i, j) = nchoosek(i-1, j-1) * (-1)^(j+1);
end
end
% Regularization for numerical stability
Tz = Tz + 1e-8 * eye(size(Tz));
% Debugging: Display Tz matrix
disp(‘Tz Matrix:’);
disp(Tz);
end
The problem is the it does not match the values as solved in the paper Electronic letters…
The solutions provided are :
Please could any body help me correcting this code to obtain the solution ? mathematics, digital image processing, digital signal processing, linear algebra MATLAB Answers — New Questions
Output Port Mapping after FPGA-in-the-loop (with Xilinx Basys3 Board)
Good day,
I have deployed a subsystem on my Xilinx Basys3 board for FIL (FPGA-in-the-loop) testing. The bitstream generated successfully and the FIL output matched with the SIMULINK model’s output. (I will use a snippet of the subsystem below to aid in describing my problem)
My next objective is to map the output (PHYFrame_out) to an output port on the BASYS3 board to physically obtain the signal. At this point I started digging around in the Xilinx project generated by the FIL workflow to manually map the output to a pin. I realized though, that the top-level VHDL module generated by MATLAB (see below) does not create an output port for PHYFrame_out (it only accepts the sysclk and sysrst). As a result, I am unable to map the signal to a pin.
Is there a step that I am missing that will allow me to perform I/O mapping from the HDL Coder itself. If not, are there any suggestions on how to map the DUT (device under test) output to an output port (something that comes to mind is editing the top-level VHDL code to include an output of my own and try to extract the signal that way). Thank you for any suggestions.Good day,
I have deployed a subsystem on my Xilinx Basys3 board for FIL (FPGA-in-the-loop) testing. The bitstream generated successfully and the FIL output matched with the SIMULINK model’s output. (I will use a snippet of the subsystem below to aid in describing my problem)
My next objective is to map the output (PHYFrame_out) to an output port on the BASYS3 board to physically obtain the signal. At this point I started digging around in the Xilinx project generated by the FIL workflow to manually map the output to a pin. I realized though, that the top-level VHDL module generated by MATLAB (see below) does not create an output port for PHYFrame_out (it only accepts the sysclk and sysrst). As a result, I am unable to map the signal to a pin.
Is there a step that I am missing that will allow me to perform I/O mapping from the HDL Coder itself. If not, are there any suggestions on how to map the DUT (device under test) output to an output port (something that comes to mind is editing the top-level VHDL code to include an output of my own and try to extract the signal that way). Thank you for any suggestions. Good day,
I have deployed a subsystem on my Xilinx Basys3 board for FIL (FPGA-in-the-loop) testing. The bitstream generated successfully and the FIL output matched with the SIMULINK model’s output. (I will use a snippet of the subsystem below to aid in describing my problem)
My next objective is to map the output (PHYFrame_out) to an output port on the BASYS3 board to physically obtain the signal. At this point I started digging around in the Xilinx project generated by the FIL workflow to manually map the output to a pin. I realized though, that the top-level VHDL module generated by MATLAB (see below) does not create an output port for PHYFrame_out (it only accepts the sysclk and sysrst). As a result, I am unable to map the signal to a pin.
Is there a step that I am missing that will allow me to perform I/O mapping from the HDL Coder itself. If not, are there any suggestions on how to map the DUT (device under test) output to an output port (something that comes to mind is editing the top-level VHDL code to include an output of my own and try to extract the signal that way). Thank you for any suggestions. fpga-in-the-loop, vivado MATLAB Answers — New Questions
Compare two irregularly sampled, noisy sinusoidal signals
I am an engineer by discipline, so I have a basic understanding of sine waves, but I am unfamiliar with signal processing techniques. I have two sets of noisy, irregularly sampled sinusoids and I have been tasked quantify how similar they are. The code below generates arrays that are similar to the data I am looking at. My data, however, was measured, so I have no prior knowledge of the amplitudes/frequencies of the sinusoids, only 3 arrays: one containing the discrete time points, and the other two containig the discrete values for signal x and signal y.
t = sort(10*rand(10000,1)); % Generate uneven sample times
x = 2*sin(pi*t) + 3*cos(2*pi*t) + rand(size(t)); % Generate signal 1
y = 2.1*sin(pi*t+0.3) + 3.1*cos(2*pi*t+0.3) + rand(size(t)); % Generate signal 2
I’d greatly appreciate any guidance/references to how to accomplish the task. Thank you for your time.I am an engineer by discipline, so I have a basic understanding of sine waves, but I am unfamiliar with signal processing techniques. I have two sets of noisy, irregularly sampled sinusoids and I have been tasked quantify how similar they are. The code below generates arrays that are similar to the data I am looking at. My data, however, was measured, so I have no prior knowledge of the amplitudes/frequencies of the sinusoids, only 3 arrays: one containing the discrete time points, and the other two containig the discrete values for signal x and signal y.
t = sort(10*rand(10000,1)); % Generate uneven sample times
x = 2*sin(pi*t) + 3*cos(2*pi*t) + rand(size(t)); % Generate signal 1
y = 2.1*sin(pi*t+0.3) + 3.1*cos(2*pi*t+0.3) + rand(size(t)); % Generate signal 2
I’d greatly appreciate any guidance/references to how to accomplish the task. Thank you for your time. I am an engineer by discipline, so I have a basic understanding of sine waves, but I am unfamiliar with signal processing techniques. I have two sets of noisy, irregularly sampled sinusoids and I have been tasked quantify how similar they are. The code below generates arrays that are similar to the data I am looking at. My data, however, was measured, so I have no prior knowledge of the amplitudes/frequencies of the sinusoids, only 3 arrays: one containing the discrete time points, and the other two containig the discrete values for signal x and signal y.
t = sort(10*rand(10000,1)); % Generate uneven sample times
x = 2*sin(pi*t) + 3*cos(2*pi*t) + rand(size(t)); % Generate signal 1
y = 2.1*sin(pi*t+0.3) + 3.1*cos(2*pi*t+0.3) + rand(size(t)); % Generate signal 2
I’d greatly appreciate any guidance/references to how to accomplish the task. Thank you for your time. fft, plomb, lomb, scargle, signal processing, discrete, discrete signal processing, dsp, fourier, irregular, noisy, irregularly sampled, noisy data, noisy sinusoid MATLAB Answers — New Questions
Error using Matlab’s publish function to create a pdf
On 3 of my students’ laptops that have Matlab installed, regardless of whether I use the publish function in the Command Window, or the publish tab at the top, I cannot get Matlab to generate a pdf. It gives me the same error on all 3 laptops:
Error using mlreportgen.re.internal.xml.transform.CompiledStylesheet
All of my other students are not having this issue on their computers. I have tried seeing if this has been asked before or other people have had this error but I am not finding anything on the mathworks website. I have taught this class for years and have never seen this error using the publish function before.On 3 of my students’ laptops that have Matlab installed, regardless of whether I use the publish function in the Command Window, or the publish tab at the top, I cannot get Matlab to generate a pdf. It gives me the same error on all 3 laptops:
Error using mlreportgen.re.internal.xml.transform.CompiledStylesheet
All of my other students are not having this issue on their computers. I have tried seeing if this has been asked before or other people have had this error but I am not finding anything on the mathworks website. I have taught this class for years and have never seen this error using the publish function before. On 3 of my students’ laptops that have Matlab installed, regardless of whether I use the publish function in the Command Window, or the publish tab at the top, I cannot get Matlab to generate a pdf. It gives me the same error on all 3 laptops:
Error using mlreportgen.re.internal.xml.transform.CompiledStylesheet
All of my other students are not having this issue on their computers. I have tried seeing if this has been asked before or other people have had this error but I am not finding anything on the mathworks website. I have taught this class for years and have never seen this error using the publish function before. publish function MATLAB Answers — New Questions
Desorption reactor design in simulink
Hello, I want to model a desorption reactor with a fixed bed containing gold-laden carbon, through which a desorbing solution passes, which extracts extra gold. I am trying to solve it using a PDE system in which I create multiple nodes, assimilating it as if it were solved using the finite difference method. Using a forward difference for the initial node, a central difference for the intermediate nodes, and a backward difference for the final node. These are relative to a distance differential.The equations are as follows.
So i tried finite differences for dc/dz with forward difference for eactor entry , central along the reactor , and backward in the exit, and dc/dt and dq/dt use integrator blocks, I consider Co= 0 kg/m3 solution and q0=4.320 kg/m3 carbon. Just considering 5 nodes , shall be more but first i want to make the first five work fine .
And each node consist on the following layout , where can be seen a time integral block term for q(carbon loading) and c(solution loading , it shows also a length step and inputs from the forwarded and current node soluction concentration(in the case of the first node)
My problem is that I am getting the same values on each node, which I don’t know if it is right the layout approach, since they should be different with relation to time and besides when i increase or decrease the input stream speed , the values in carbon and solution loading not change at all. thanks in advance
The model file is attached next: Reactor processHello, I want to model a desorption reactor with a fixed bed containing gold-laden carbon, through which a desorbing solution passes, which extracts extra gold. I am trying to solve it using a PDE system in which I create multiple nodes, assimilating it as if it were solved using the finite difference method. Using a forward difference for the initial node, a central difference for the intermediate nodes, and a backward difference for the final node. These are relative to a distance differential.The equations are as follows.
So i tried finite differences for dc/dz with forward difference for eactor entry , central along the reactor , and backward in the exit, and dc/dt and dq/dt use integrator blocks, I consider Co= 0 kg/m3 solution and q0=4.320 kg/m3 carbon. Just considering 5 nodes , shall be more but first i want to make the first five work fine .
And each node consist on the following layout , where can be seen a time integral block term for q(carbon loading) and c(solution loading , it shows also a length step and inputs from the forwarded and current node soluction concentration(in the case of the first node)
My problem is that I am getting the same values on each node, which I don’t know if it is right the layout approach, since they should be different with relation to time and besides when i increase or decrease the input stream speed , the values in carbon and solution loading not change at all. thanks in advance
The model file is attached next: Reactor process Hello, I want to model a desorption reactor with a fixed bed containing gold-laden carbon, through which a desorbing solution passes, which extracts extra gold. I am trying to solve it using a PDE system in which I create multiple nodes, assimilating it as if it were solved using the finite difference method. Using a forward difference for the initial node, a central difference for the intermediate nodes, and a backward difference for the final node. These are relative to a distance differential.The equations are as follows.
So i tried finite differences for dc/dz with forward difference for eactor entry , central along the reactor , and backward in the exit, and dc/dt and dq/dt use integrator blocks, I consider Co= 0 kg/m3 solution and q0=4.320 kg/m3 carbon. Just considering 5 nodes , shall be more but first i want to make the first five work fine .
And each node consist on the following layout , where can be seen a time integral block term for q(carbon loading) and c(solution loading , it shows also a length step and inputs from the forwarded and current node soluction concentration(in the case of the first node)
My problem is that I am getting the same values on each node, which I don’t know if it is right the layout approach, since they should be different with relation to time and besides when i increase or decrease the input stream speed , the values in carbon and solution loading not change at all. thanks in advance
The model file is attached next: Reactor process simulink MATLAB Answers — New Questions
Variable number of inputs in inputdlg with pre-selected values when inputs equals 6
Sometimes I want to replace the column headings in a uitable. I have several uitables and each can have a variable number of columns so I have the following code which uses an inputdlg but with a variable number of inputs.
T=app.UITable;
data=T.Data;
[rows,cols]=size(data)
ReportMessage(app,[‘UITABLE cols: ‘,num2str(cols)]);
dlgtitle = ‘Modify Columns Headings….’;
prompts=compose(‘Col %d’,1:cols);
y=inputdlg(prompts,dlgtitle);
T.ColumnName=y;
When the number of columns is 6, I want to pre-select the input entries. Normally I would use this
definput = {‘100′,’1′,’31.72′,’0′,’123′,’78’};
But this doesn’t work
if cols==6
prompts=compose(‘Col %d’,1:cols);
definput = {‘100′,’1′,’31.72′,’0′,’123′,’78’};
y=inputdlg(prompts,dlgtitle,definput);
end
T.ColumnName=y;
But this doesn’t workSometimes I want to replace the column headings in a uitable. I have several uitables and each can have a variable number of columns so I have the following code which uses an inputdlg but with a variable number of inputs.
T=app.UITable;
data=T.Data;
[rows,cols]=size(data)
ReportMessage(app,[‘UITABLE cols: ‘,num2str(cols)]);
dlgtitle = ‘Modify Columns Headings….’;
prompts=compose(‘Col %d’,1:cols);
y=inputdlg(prompts,dlgtitle);
T.ColumnName=y;
When the number of columns is 6, I want to pre-select the input entries. Normally I would use this
definput = {‘100′,’1′,’31.72′,’0′,’123′,’78’};
But this doesn’t work
if cols==6
prompts=compose(‘Col %d’,1:cols);
definput = {‘100′,’1′,’31.72′,’0′,’123′,’78’};
y=inputdlg(prompts,dlgtitle,definput);
end
T.ColumnName=y;
But this doesn’t work Sometimes I want to replace the column headings in a uitable. I have several uitables and each can have a variable number of columns so I have the following code which uses an inputdlg but with a variable number of inputs.
T=app.UITable;
data=T.Data;
[rows,cols]=size(data)
ReportMessage(app,[‘UITABLE cols: ‘,num2str(cols)]);
dlgtitle = ‘Modify Columns Headings….’;
prompts=compose(‘Col %d’,1:cols);
y=inputdlg(prompts,dlgtitle);
T.ColumnName=y;
When the number of columns is 6, I want to pre-select the input entries. Normally I would use this
definput = {‘100′,’1′,’31.72′,’0′,’123′,’78’};
But this doesn’t work
if cols==6
prompts=compose(‘Col %d’,1:cols);
definput = {‘100′,’1′,’31.72′,’0′,’123′,’78’};
y=inputdlg(prompts,dlgtitle,definput);
end
T.ColumnName=y;
But this doesn’t work inputdlg MATLAB Answers — New Questions
Image Processing getting HSV components from colored image
I am trying to the the hue, saturation and value images from an image (originally colored). I converted the image using rgb2hsv() function but I am confused about how to get the 3 images from there.
Thanks in advance!I am trying to the the hue, saturation and value images from an image (originally colored). I converted the image using rgb2hsv() function but I am confused about how to get the 3 images from there.
Thanks in advance! I am trying to the the hue, saturation and value images from an image (originally colored). I converted the image using rgb2hsv() function but I am confused about how to get the 3 images from there.
Thanks in advance! image processing, hsv, image components MATLAB Answers — New Questions
Neglection of [outport]variable generated for bus assignment block
My intention is to generate th code as mentioned below
void computeArea() {
rectangle.area = rectangle.length * rectangle.width;
}My intention is to generate th code as mentioned below
void computeArea() {
rectangle.area = rectangle.length * rectangle.width;
} My intention is to generate th code as mentioned below
void computeArea() {
rectangle.area = rectangle.length * rectangle.width;
} bus assignment ouport |bus inp MATLAB Answers — New Questions