Author: PuTI
EEG bandpass filtering locutoff and hicutoff syntax
I have been confused with this basic question for a while. If I want to keep the EEG data ranging from 0.05Hz- 80Hz when doing the bandpass filtering step, should I run: EEG = pop_eegfiltnew(EEG, ‘locutoff’, 0.05, ‘hicutoff’, 80)or EEG = pop_eegfiltnew(EEG, ‘locutoff’, 0.05, ‘hicutoff’, 80, ‘revfilt’, 1)? Thank you so much for anawering this question!I have been confused with this basic question for a while. If I want to keep the EEG data ranging from 0.05Hz- 80Hz when doing the bandpass filtering step, should I run: EEG = pop_eegfiltnew(EEG, ‘locutoff’, 0.05, ‘hicutoff’, 80)or EEG = pop_eegfiltnew(EEG, ‘locutoff’, 0.05, ‘hicutoff’, 80, ‘revfilt’, 1)? Thank you so much for anawering this question! I have been confused with this basic question for a while. If I want to keep the EEG data ranging from 0.05Hz- 80Hz when doing the bandpass filtering step, should I run: EEG = pop_eegfiltnew(EEG, ‘locutoff’, 0.05, ‘hicutoff’, 80)or EEG = pop_eegfiltnew(EEG, ‘locutoff’, 0.05, ‘hicutoff’, 80, ‘revfilt’, 1)? Thank you so much for anawering this question! eeg, bandpass filtering MATLAB Answers — New Questions
Copy Legend from UIAxes to another UIAxes
Hello,i want to copy a plot on a uiaxes to another uiaxes and can do using the following – but I can’t get the legend to copy accross (I want to avoid using the downloadedable copyuiaxes for now)
ax1=app.UIAxes3 % My main axes for plotting
ax1.Children
L1=ax1.Legend % This works
L1s=L1.String{1} % and this
f2=figure; ax2=axes(f2);
new_children=copyobj(ax1.Children,ax2);
makeGraphBlack(app,ax2,’k’,’w’); % My own function to change appearance (background & grid)
% Copy desired axes properties
ax2.XLim=ax1.XLim; ax2.YLim=ax1.YLim;
ax2.Title.String=ax1.Title.String;
ax2.XLabel.String=ax1.XLabel.String;
ax2.YLabel.String=ax1.YLabel.String;
propsToCopy={‘FontSize’,’Color’,’GridLineStyle’};
for prop=propsToCopy
set(ax2,prop{1},get(ax1,prop{1}));
end
%Copy Legend
legend(ax2)
ax2.Legend=L1;
legend.TextColor = ‘w’;
This gives me the error message:
Unrecognized function or variable ‘legend’.
Also I notice copyobj doesn’t retain the colours of the plots, so I thought adding ‘Color’ to propsToCopy would do it. Do I have to go the route of finding the line objects of the ax1 children, and then dig down into each of their colors – or is there a quicker way?
ThanksHello,i want to copy a plot on a uiaxes to another uiaxes and can do using the following – but I can’t get the legend to copy accross (I want to avoid using the downloadedable copyuiaxes for now)
ax1=app.UIAxes3 % My main axes for plotting
ax1.Children
L1=ax1.Legend % This works
L1s=L1.String{1} % and this
f2=figure; ax2=axes(f2);
new_children=copyobj(ax1.Children,ax2);
makeGraphBlack(app,ax2,’k’,’w’); % My own function to change appearance (background & grid)
% Copy desired axes properties
ax2.XLim=ax1.XLim; ax2.YLim=ax1.YLim;
ax2.Title.String=ax1.Title.String;
ax2.XLabel.String=ax1.XLabel.String;
ax2.YLabel.String=ax1.YLabel.String;
propsToCopy={‘FontSize’,’Color’,’GridLineStyle’};
for prop=propsToCopy
set(ax2,prop{1},get(ax1,prop{1}));
end
%Copy Legend
legend(ax2)
ax2.Legend=L1;
legend.TextColor = ‘w’;
This gives me the error message:
Unrecognized function or variable ‘legend’.
Also I notice copyobj doesn’t retain the colours of the plots, so I thought adding ‘Color’ to propsToCopy would do it. Do I have to go the route of finding the line objects of the ax1 children, and then dig down into each of their colors – or is there a quicker way?
Thanks Hello,i want to copy a plot on a uiaxes to another uiaxes and can do using the following – but I can’t get the legend to copy accross (I want to avoid using the downloadedable copyuiaxes for now)
ax1=app.UIAxes3 % My main axes for plotting
ax1.Children
L1=ax1.Legend % This works
L1s=L1.String{1} % and this
f2=figure; ax2=axes(f2);
new_children=copyobj(ax1.Children,ax2);
makeGraphBlack(app,ax2,’k’,’w’); % My own function to change appearance (background & grid)
% Copy desired axes properties
ax2.XLim=ax1.XLim; ax2.YLim=ax1.YLim;
ax2.Title.String=ax1.Title.String;
ax2.XLabel.String=ax1.XLabel.String;
ax2.YLabel.String=ax1.YLabel.String;
propsToCopy={‘FontSize’,’Color’,’GridLineStyle’};
for prop=propsToCopy
set(ax2,prop{1},get(ax1,prop{1}));
end
%Copy Legend
legend(ax2)
ax2.Legend=L1;
legend.TextColor = ‘w’;
This gives me the error message:
Unrecognized function or variable ‘legend’.
Also I notice copyobj doesn’t retain the colours of the plots, so I thought adding ‘Color’ to propsToCopy would do it. Do I have to go the route of finding the line objects of the ax1 children, and then dig down into each of their colors – or is there a quicker way?
Thanks uiaxes, legend, copyobj MATLAB Answers — New Questions
增量谐波平衡法(IHB)
Hello everyone, I am a beginner in Matlab programming and have been trying to solve the differential equation system for incremental harmonic balance (IHB) given below. I have a MATLAB program, but there seems to be a problem and the analysis results are not satisfactory. We would greatly appreciate any assistance or related work. Thank you in advance.
matlab code
clear all
close all
clc
tic
syms t
%========输入基本参数(已知条件)======
%========duffing 方程得参数===========
a=0.95; %负刚度弹簧在静平衡位置的长度无量纲
lambda=0.085;
lambda_s=-4*lambda*(a-1)/(4*lambda*(a-1)+a);
miu=0.00001; %质量比
xi=0.05;%正刚度阻尼比
xi_b1=0.001;%负刚度装置阻尼比
z=0.06;%幅值
p0=-4*lambda*(1/(a^2)^(1/2)-1);
p1=(2*lambda)/(a^2)^(3/2);
p2=-(3*lambda)/(2*(a^2)^(5/2));
p3=(5*lambda)/(4*(a^2)^(7/2));
p4=-(35*lambda)/(32*(a^2)^(9/2));
p5=(63*lambda)/(64*(a^2)^(11/2));
m=[1,0;0,miu];% m惯性项系数
k=[1+lambda_s,-lambda_s;-lambda_s,lambda_s+p0];% k一次项系数
f=[z;0];% f激励幅值
c=[2*xi,0;0,2*xi_b1];% c阻尼系数
%=====控制参数
omg0=0.005;domg=0.0183;%频率比初始值与增量
%%%%%%能否收敛,delta_s和Nd的取值至关重要
%Nd一般要大于2,易收敛时Nd不宜太大,Nd越小,取值点越密集。非线性较强,Nd取值应稍大一些
delta_s=0.02;%弧长增量值
Nd=1;
Num_Pre_step=4; %预测解需要预测Num_Pre_step步
Num_Incremental_step=160; %程序总共计算Num_Incremental_step步
%========设置谐波矩阵=================
Cs=[ cos(t) sin(t) cos(2*t) sin(2*t)];
S=blkdiag(Cs,Cs);
S1=diff(S,t,1);
S2=diff(S,t,2);
%========设置A矩阵初值================
A1=[ 0.1 0.1 0.1 0.1];%上部结构位移响应的谐波系数
A2=[ 0.1 0.1 0.1 0.1];%调谐装置位移响应的谐波系数
A=[A1,A2]’;%傅里叶系数矩阵
length_A=length(A);
%========质量矩阵m====================
%========刚度矩阵k====================
%========阻尼矩阵k====================
%========外激励矩阵f==================
%========非线性刚度矩阵===============
A0=[zeros(1,length(A1)),A(1:length(A2),:)’]’;
q=(S*A0)’;
kn3=[0;p1]*q.^2;
kn5=[0;p2]*q.^4;
kn7=[0;p3]*q.^6;
kn9=[0;p4]*q.^8;
kn11=[0;p5]*q.^10;
%================
%========积分过程==
fm=inline(S’*m*S2);
M=quadv(fm,0,2*pi);%质量矩阵
fk=inline(S’*k*S);
K=quadv(fk,0,2*pi);%线性刚度矩阵
fc=inline(S’*c*S1);
C=quadv(fc,0,2*pi);%阻尼矩阵
fkn3=inline(S’*kn3*S);
KN3=quadv(fkn3,0,2*pi);%非线性矩阵
fkn5=inline(S’*kn5*S);
KN5=quadv(fkn5,0,2*pi);%非线性矩阵
fkn7=inline(S’*kn7*S);
KN7=quadv(fkn7,0,2*pi);%非线性矩阵
fkn9=inline(S’*kn9*S);
KN9=quadv(fkn9,0,2*pi);%非线性矩阵
fkn11=inline(S’*kn11*S);
KN11=quadv(fkn11,0,2*pi);%非线性矩阵
ff=inline(S’*f*cos(t));
F=quadv(ff,0,2*pi);%激励矩阵
%=========带入公式,公式推导可见陈的书
Kmc=omg0^2*M+omg0*C+K+3*KN3+5*KN5+7*KN7+9*KN9+11*KN11;
R=-F-(omg0^2*M+omg0*C+K+KN3+KN5+KN7+KN9+KN11)*A;
Rmc=-(2*omg0*M+C)*A;
Delta_A=inv(Kmc)*R;
%=======开始迭代过程
epsR=1e-4;
i=1;
X=zeros(length_A+1,4); %建立0矩阵便于保存四个解用于预测
s=zeros(1,3);
Harmonic_A=[]; %用于保存每一个解的谐波项系数
Result_A1=[ ];
for i=1:Num_Pre_step %该部分没有应用弧长法,预先求得一部分解便于弧长法的预测
n=1;tol=1;
while tol>epsR
A=A+Delta_A;
%====回代非线性刚度矩阵,计算下一次循环过程的非线性刚度矩阵
A0=[zeros(1,length(A1)),A(1:length(A2),:)’]’;
q=(S*A0)’;
kn3=[0;p1]*q.^2;
kn5=[0;p2]*q.^4;
kn7=[0;p3]*q.^6;
kn9=[0;p4]*q.^8;
kn11=[0;p5]*q.^10;
fkn3=inline(S’*kn3*S);
KN3=quadv(fkn3,0,2*pi);%非线性矩阵
fkn5=inline(S’*kn5*S);
KN5=quadv(fkn5,0,2*pi);%非线性矩阵
fkn7=inline(S’*kn7*S);
KN7=quadv(fkn7,0,2*pi);%非线性矩阵
fkn9=inline(S’*kn9*S);
KN9=quadv(fkn9,0,2*pi);%非线性矩阵
fkn11=inline(S’*kn11*S);
KN11=quadv(fkn11,0,2*pi);%非线性矩阵
%====再一次计算
Kmc=omg0^2*M+omg0*C+K+3*KN3+5*KN5+7*KN7+9*KN9+11*KN11;
R=-F-(omg0^2*M+omg0*C+K+KN3+KN5+KN7+KN9+KN11)*A;
Rmc=-(2*omg0*M+C)*A;
tol=norm(R);
Delta_A=inv(Kmc)*R;
if(n>60)
disp(‘迭代步数太多,可能不收敛’)
return
end
n=n+1;
end
I3=n-1;
disp([‘增量步=’ num2str(i),’ 迭代次数=’ num2str(I3),’ 本增量步弧长=’ num2str(delta_s),’ 已计算到频率=’ num2str(omg0)])
Harmonic_A=[Harmonic_A;A’];
%%%%%%%%%%%%%保存最新的四组解,便于弧长法预测
for p=1:3
X(:,p)=X(:,p+1);
end
X(1:length_A,4)=A;
X(length_A+1,4)=omg0;
p=0;
%%%%%%%%%%%%%
Frequency(i)=omg0;
% Amplitude11(i)=sqrt(A(2)^2+A(4)^2);
% Amplitude12(i)=sqrt(A(3)^2+A(5)^2);
Amplitude(i)=sqrt(A(2)^2+A(1)^2+A(3)^2+A(4)^2);
Result_A1(:,i)=A;
omg0=omg0+domg;
i=i+1;
end
% 以下是结合了弧长法的增量谐波平衡法
Result_A2=[];
for i=Num_Pre_step+1:Num_Incremental_step %%%%取Num_Incremental_step个增量步
n=1;tol=1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%
for kk=1:3
s(kk)=norm(X(:,kk+1)-X(:,kk));
end
tt(1)=0;tt(2)=s(1);tt(3)=tt(2)+s(2);tt(4)=tt(3)+s(3);tt(5)=tt(4)+delta_s;
PreValue_X=zeros(length_A+1,1);
for ii=1:4
aa=1;
for jj=1:4
if jj~=ii
aa=aa*((tt(5)-tt(jj))/(tt(ii)-tt(jj)));
end
end
PreValue_X=PreValue_X+aa*X(:,ii);
end
A=PreValue_X(1:length_A);
omg0=PreValue_X(length_A+1);
%%%%%%%%%%%%%%%%%%%%%%%%%% 以上这部分为弧长法,根据已经计算得到的四组解预测下一个解的过程,可见陈的书P177
%%%%%计算非线性刚度矩阵
A0=[zeros(1,length(A1)),A(1:length(A2),:)’]’;
q=(S*A0)’;
kn3=[0;p1]*q.^2;
kn5=[0;p2]*q.^4;
kn7=[0;p3]*q.^6;
kn9=[0;p4]*q.^8;
kn11=[0;p5]*q.^10;
fkn3=inline(S’*kn3*S);
KN3=quadv(fkn3,0,2*pi);%非线性矩阵
fkn5=inline(S’*kn5*S);
KN5=quadv(fkn5,0,2*pi);%非线性矩阵
fkn7=inline(S’*kn7*S);
KN7=quadv(fkn7,0,2*pi);%非线性矩阵
fkn9=inline(S’*kn9*S);
KN9=quadv(fkn9,0,2*pi);%非线性矩阵
fkn11=inline(S’*kn11*S);
KN11=quadv(fkn11,0,2*pi);%非线性矩阵
Kmc=omg0^2*M+omg0*C+K+3*KN3+5*KN5+7*KN7+9*KN9+11*KN11;
R=-F-(omg0^2*M+omg0*C+K+KN3+KN5+KN7+KN9+KN11)*A;
Rmc=-(2*omg0*M+C)*A;
%%%%%%%%%%%%判断并寻找控制变量
DELTA_X=PreValue_X-X(:,4); %DELTA_X是预测解与上一增量步的差值,只用来寻找最大值元素,与Delta_X的意义不同。Delta_X是每一个迭代步产生的插值
[~,flag]=max(abs(DELTA_X(1:length_A)));%找到绝对值最大的元素及其下标索引Note_flag,注意要把omg0排除在外,找delta_A中的最大值元素
Note_flag=flag;
%%%%%%%%%%%%%%%%%%%%处理求得的解,得到我们所需要的Delta_A和domg
Kmc(:,Note_flag)=-Rmc(:,1);
Kmc=Kmc(1:length_A,1:length_A);
Delta_X=inv(Kmc)*R;
Delta_X(length_A+1)=0;
Delta_X(length_A+1)=Delta_X(Note_flag);
Delta_X(Note_flag)=0;
Delta_A=Delta_X(1:length_A);
domg=Delta_X(length_A+1);
%A00=[w0;A0(2:6,1)];
A=A+Delta_A;
omg0=omg0+domg;
%%%%%%%%%%%%%%%%%%%%%%%%%下面是每个增量步内的循环迭代
while tol>epsR
%====回代非线性刚度矩阵,计算下一次循环过程的非线性刚度矩阵
A0=[zeros(1,length(A1)),A(1:length(A2),:)’]’;
q=(S*A0)’;
kn3=[0;p1]*q.^2;
kn5=[0;p2]*q.^4;
kn7=[0;p3]*q.^6;
kn9=[0;p4]*q.^8;
kn11=[0;p5]*q.^10;
fkn3=inline(S’*kn3*S);
KN3=quadv(fkn3,0,2*pi);%非线性矩阵
fkn5=inline(S’*kn5*S);
KN5=quadv(fkn5,0,2*pi);%非线性矩阵
fkn7=inline(S’*kn7*S);
KN7=quadv(fkn7,0,2*pi);%非线性矩阵
fkn9=inline(S’*kn9*S);
KN9=quadv(fkn9,0,2*pi);%非线性矩阵
fkn11=inline(S’*kn11*S);
KN11=quadv(fkn11,0,2*pi);%非线性矩阵
%%%%%%%%%%%%%%%%
Kmc=omg0^2*M+omg0*C+K+3*KN3+5*KN5+7*KN7+9*KN9+11*KN11;
R=-F-(omg0^2*M+omg0*C+K+KN3+KN5+KN7+KN9+KN11)*A;
Rmc=-(2*omg0*M+C)*A;
tol=norm(R);
Kmc(:,Note_flag)=-Rmc(:,1);
Kmc=Kmc(1:length_A,1:length_A);
Delta_X=inv(Kmc)*R;
Delta_X(length_A+1)=0;
Delta_X(length_A+1)=Delta_X(Note_flag);
Delta_X(Note_flag)=0;
Delta_A=Delta_X(1:length_A);
domg=Delta_X(length_A+1);
%A00=[w0;A0(2:6,1)];
A=A+Delta_A;
omg0=omg0+domg;
if(n>60)
disp(‘迭代步数太多,可能不收敛’)
return
end
n=n+1;
end
I3=n-1;
disp([‘增量步=’ num2str(i),’ 迭代次数=’ num2str(I3),’ 本增量步弧长=’ num2str(delta_s),’ 已计算到频率比=’ num2str(omg0)])
Harmonic_A=[Harmonic_A;A’];
delta_s=delta_s*Nd/I3;
% [i I3 delta_s omg0]
%%%%%%%%%%%%%保存最新的四组解,用于预测
for p=1:3
X(:,p)=X(:,p+1);
end
X(1:length_A,4)=A;
X(length_A+1,4)=omg0;
p=0;
%%%%%%%%%%%%%
Frequency(i)=omg0;
% Amplitude11(i)=sqrt(A(2)^2+A(4)^2);
% Amplitude12(i)=sqrt(A(3)^2+A(5)^2);
Amplitude(i)=sqrt(A(2)^2+A(1)^2+A(3)^2+A(4)^2);
Result_A2(:,i)=A;
i=i+1;
end
Result_A= [Result_A1,zeros(length(A),Num_Incremental_step-Num_Pre_step)]+ Result_A2;
% figure(1)
% plot(Frequency,Amplitude11,’o-‘,’linewidth’,2,’color’,’r’);
% xlabel(‘Frequency’);
% ylabel(‘Amplitude’);
% figure(2)
% plot(Frequency,Amplitude12,’o-‘,’linewidth’,2,’color’,’b’);
% xlabel(‘Frequency’);
% ylabel(‘Amplitude’);
figure(3)
plot(Frequency,Amplitude,’o-‘,’linewidth’,2,’color’,’b’);
xlabel(‘Frequency’);
ylabel(‘Amplitude’);
grid on
toc
Warning: The maximum function count has been exceeded; May have singularity.Hello everyone, I am a beginner in Matlab programming and have been trying to solve the differential equation system for incremental harmonic balance (IHB) given below. I have a MATLAB program, but there seems to be a problem and the analysis results are not satisfactory. We would greatly appreciate any assistance or related work. Thank you in advance.
matlab code
clear all
close all
clc
tic
syms t
%========输入基本参数(已知条件)======
%========duffing 方程得参数===========
a=0.95; %负刚度弹簧在静平衡位置的长度无量纲
lambda=0.085;
lambda_s=-4*lambda*(a-1)/(4*lambda*(a-1)+a);
miu=0.00001; %质量比
xi=0.05;%正刚度阻尼比
xi_b1=0.001;%负刚度装置阻尼比
z=0.06;%幅值
p0=-4*lambda*(1/(a^2)^(1/2)-1);
p1=(2*lambda)/(a^2)^(3/2);
p2=-(3*lambda)/(2*(a^2)^(5/2));
p3=(5*lambda)/(4*(a^2)^(7/2));
p4=-(35*lambda)/(32*(a^2)^(9/2));
p5=(63*lambda)/(64*(a^2)^(11/2));
m=[1,0;0,miu];% m惯性项系数
k=[1+lambda_s,-lambda_s;-lambda_s,lambda_s+p0];% k一次项系数
f=[z;0];% f激励幅值
c=[2*xi,0;0,2*xi_b1];% c阻尼系数
%=====控制参数
omg0=0.005;domg=0.0183;%频率比初始值与增量
%%%%%%能否收敛,delta_s和Nd的取值至关重要
%Nd一般要大于2,易收敛时Nd不宜太大,Nd越小,取值点越密集。非线性较强,Nd取值应稍大一些
delta_s=0.02;%弧长增量值
Nd=1;
Num_Pre_step=4; %预测解需要预测Num_Pre_step步
Num_Incremental_step=160; %程序总共计算Num_Incremental_step步
%========设置谐波矩阵=================
Cs=[ cos(t) sin(t) cos(2*t) sin(2*t)];
S=blkdiag(Cs,Cs);
S1=diff(S,t,1);
S2=diff(S,t,2);
%========设置A矩阵初值================
A1=[ 0.1 0.1 0.1 0.1];%上部结构位移响应的谐波系数
A2=[ 0.1 0.1 0.1 0.1];%调谐装置位移响应的谐波系数
A=[A1,A2]’;%傅里叶系数矩阵
length_A=length(A);
%========质量矩阵m====================
%========刚度矩阵k====================
%========阻尼矩阵k====================
%========外激励矩阵f==================
%========非线性刚度矩阵===============
A0=[zeros(1,length(A1)),A(1:length(A2),:)’]’;
q=(S*A0)’;
kn3=[0;p1]*q.^2;
kn5=[0;p2]*q.^4;
kn7=[0;p3]*q.^6;
kn9=[0;p4]*q.^8;
kn11=[0;p5]*q.^10;
%================
%========积分过程==
fm=inline(S’*m*S2);
M=quadv(fm,0,2*pi);%质量矩阵
fk=inline(S’*k*S);
K=quadv(fk,0,2*pi);%线性刚度矩阵
fc=inline(S’*c*S1);
C=quadv(fc,0,2*pi);%阻尼矩阵
fkn3=inline(S’*kn3*S);
KN3=quadv(fkn3,0,2*pi);%非线性矩阵
fkn5=inline(S’*kn5*S);
KN5=quadv(fkn5,0,2*pi);%非线性矩阵
fkn7=inline(S’*kn7*S);
KN7=quadv(fkn7,0,2*pi);%非线性矩阵
fkn9=inline(S’*kn9*S);
KN9=quadv(fkn9,0,2*pi);%非线性矩阵
fkn11=inline(S’*kn11*S);
KN11=quadv(fkn11,0,2*pi);%非线性矩阵
ff=inline(S’*f*cos(t));
F=quadv(ff,0,2*pi);%激励矩阵
%=========带入公式,公式推导可见陈的书
Kmc=omg0^2*M+omg0*C+K+3*KN3+5*KN5+7*KN7+9*KN9+11*KN11;
R=-F-(omg0^2*M+omg0*C+K+KN3+KN5+KN7+KN9+KN11)*A;
Rmc=-(2*omg0*M+C)*A;
Delta_A=inv(Kmc)*R;
%=======开始迭代过程
epsR=1e-4;
i=1;
X=zeros(length_A+1,4); %建立0矩阵便于保存四个解用于预测
s=zeros(1,3);
Harmonic_A=[]; %用于保存每一个解的谐波项系数
Result_A1=[ ];
for i=1:Num_Pre_step %该部分没有应用弧长法,预先求得一部分解便于弧长法的预测
n=1;tol=1;
while tol>epsR
A=A+Delta_A;
%====回代非线性刚度矩阵,计算下一次循环过程的非线性刚度矩阵
A0=[zeros(1,length(A1)),A(1:length(A2),:)’]’;
q=(S*A0)’;
kn3=[0;p1]*q.^2;
kn5=[0;p2]*q.^4;
kn7=[0;p3]*q.^6;
kn9=[0;p4]*q.^8;
kn11=[0;p5]*q.^10;
fkn3=inline(S’*kn3*S);
KN3=quadv(fkn3,0,2*pi);%非线性矩阵
fkn5=inline(S’*kn5*S);
KN5=quadv(fkn5,0,2*pi);%非线性矩阵
fkn7=inline(S’*kn7*S);
KN7=quadv(fkn7,0,2*pi);%非线性矩阵
fkn9=inline(S’*kn9*S);
KN9=quadv(fkn9,0,2*pi);%非线性矩阵
fkn11=inline(S’*kn11*S);
KN11=quadv(fkn11,0,2*pi);%非线性矩阵
%====再一次计算
Kmc=omg0^2*M+omg0*C+K+3*KN3+5*KN5+7*KN7+9*KN9+11*KN11;
R=-F-(omg0^2*M+omg0*C+K+KN3+KN5+KN7+KN9+KN11)*A;
Rmc=-(2*omg0*M+C)*A;
tol=norm(R);
Delta_A=inv(Kmc)*R;
if(n>60)
disp(‘迭代步数太多,可能不收敛’)
return
end
n=n+1;
end
I3=n-1;
disp([‘增量步=’ num2str(i),’ 迭代次数=’ num2str(I3),’ 本增量步弧长=’ num2str(delta_s),’ 已计算到频率=’ num2str(omg0)])
Harmonic_A=[Harmonic_A;A’];
%%%%%%%%%%%%%保存最新的四组解,便于弧长法预测
for p=1:3
X(:,p)=X(:,p+1);
end
X(1:length_A,4)=A;
X(length_A+1,4)=omg0;
p=0;
%%%%%%%%%%%%%
Frequency(i)=omg0;
% Amplitude11(i)=sqrt(A(2)^2+A(4)^2);
% Amplitude12(i)=sqrt(A(3)^2+A(5)^2);
Amplitude(i)=sqrt(A(2)^2+A(1)^2+A(3)^2+A(4)^2);
Result_A1(:,i)=A;
omg0=omg0+domg;
i=i+1;
end
% 以下是结合了弧长法的增量谐波平衡法
Result_A2=[];
for i=Num_Pre_step+1:Num_Incremental_step %%%%取Num_Incremental_step个增量步
n=1;tol=1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%
for kk=1:3
s(kk)=norm(X(:,kk+1)-X(:,kk));
end
tt(1)=0;tt(2)=s(1);tt(3)=tt(2)+s(2);tt(4)=tt(3)+s(3);tt(5)=tt(4)+delta_s;
PreValue_X=zeros(length_A+1,1);
for ii=1:4
aa=1;
for jj=1:4
if jj~=ii
aa=aa*((tt(5)-tt(jj))/(tt(ii)-tt(jj)));
end
end
PreValue_X=PreValue_X+aa*X(:,ii);
end
A=PreValue_X(1:length_A);
omg0=PreValue_X(length_A+1);
%%%%%%%%%%%%%%%%%%%%%%%%%% 以上这部分为弧长法,根据已经计算得到的四组解预测下一个解的过程,可见陈的书P177
%%%%%计算非线性刚度矩阵
A0=[zeros(1,length(A1)),A(1:length(A2),:)’]’;
q=(S*A0)’;
kn3=[0;p1]*q.^2;
kn5=[0;p2]*q.^4;
kn7=[0;p3]*q.^6;
kn9=[0;p4]*q.^8;
kn11=[0;p5]*q.^10;
fkn3=inline(S’*kn3*S);
KN3=quadv(fkn3,0,2*pi);%非线性矩阵
fkn5=inline(S’*kn5*S);
KN5=quadv(fkn5,0,2*pi);%非线性矩阵
fkn7=inline(S’*kn7*S);
KN7=quadv(fkn7,0,2*pi);%非线性矩阵
fkn9=inline(S’*kn9*S);
KN9=quadv(fkn9,0,2*pi);%非线性矩阵
fkn11=inline(S’*kn11*S);
KN11=quadv(fkn11,0,2*pi);%非线性矩阵
Kmc=omg0^2*M+omg0*C+K+3*KN3+5*KN5+7*KN7+9*KN9+11*KN11;
R=-F-(omg0^2*M+omg0*C+K+KN3+KN5+KN7+KN9+KN11)*A;
Rmc=-(2*omg0*M+C)*A;
%%%%%%%%%%%%判断并寻找控制变量
DELTA_X=PreValue_X-X(:,4); %DELTA_X是预测解与上一增量步的差值,只用来寻找最大值元素,与Delta_X的意义不同。Delta_X是每一个迭代步产生的插值
[~,flag]=max(abs(DELTA_X(1:length_A)));%找到绝对值最大的元素及其下标索引Note_flag,注意要把omg0排除在外,找delta_A中的最大值元素
Note_flag=flag;
%%%%%%%%%%%%%%%%%%%%处理求得的解,得到我们所需要的Delta_A和domg
Kmc(:,Note_flag)=-Rmc(:,1);
Kmc=Kmc(1:length_A,1:length_A);
Delta_X=inv(Kmc)*R;
Delta_X(length_A+1)=0;
Delta_X(length_A+1)=Delta_X(Note_flag);
Delta_X(Note_flag)=0;
Delta_A=Delta_X(1:length_A);
domg=Delta_X(length_A+1);
%A00=[w0;A0(2:6,1)];
A=A+Delta_A;
omg0=omg0+domg;
%%%%%%%%%%%%%%%%%%%%%%%%%下面是每个增量步内的循环迭代
while tol>epsR
%====回代非线性刚度矩阵,计算下一次循环过程的非线性刚度矩阵
A0=[zeros(1,length(A1)),A(1:length(A2),:)’]’;
q=(S*A0)’;
kn3=[0;p1]*q.^2;
kn5=[0;p2]*q.^4;
kn7=[0;p3]*q.^6;
kn9=[0;p4]*q.^8;
kn11=[0;p5]*q.^10;
fkn3=inline(S’*kn3*S);
KN3=quadv(fkn3,0,2*pi);%非线性矩阵
fkn5=inline(S’*kn5*S);
KN5=quadv(fkn5,0,2*pi);%非线性矩阵
fkn7=inline(S’*kn7*S);
KN7=quadv(fkn7,0,2*pi);%非线性矩阵
fkn9=inline(S’*kn9*S);
KN9=quadv(fkn9,0,2*pi);%非线性矩阵
fkn11=inline(S’*kn11*S);
KN11=quadv(fkn11,0,2*pi);%非线性矩阵
%%%%%%%%%%%%%%%%
Kmc=omg0^2*M+omg0*C+K+3*KN3+5*KN5+7*KN7+9*KN9+11*KN11;
R=-F-(omg0^2*M+omg0*C+K+KN3+KN5+KN7+KN9+KN11)*A;
Rmc=-(2*omg0*M+C)*A;
tol=norm(R);
Kmc(:,Note_flag)=-Rmc(:,1);
Kmc=Kmc(1:length_A,1:length_A);
Delta_X=inv(Kmc)*R;
Delta_X(length_A+1)=0;
Delta_X(length_A+1)=Delta_X(Note_flag);
Delta_X(Note_flag)=0;
Delta_A=Delta_X(1:length_A);
domg=Delta_X(length_A+1);
%A00=[w0;A0(2:6,1)];
A=A+Delta_A;
omg0=omg0+domg;
if(n>60)
disp(‘迭代步数太多,可能不收敛’)
return
end
n=n+1;
end
I3=n-1;
disp([‘增量步=’ num2str(i),’ 迭代次数=’ num2str(I3),’ 本增量步弧长=’ num2str(delta_s),’ 已计算到频率比=’ num2str(omg0)])
Harmonic_A=[Harmonic_A;A’];
delta_s=delta_s*Nd/I3;
% [i I3 delta_s omg0]
%%%%%%%%%%%%%保存最新的四组解,用于预测
for p=1:3
X(:,p)=X(:,p+1);
end
X(1:length_A,4)=A;
X(length_A+1,4)=omg0;
p=0;
%%%%%%%%%%%%%
Frequency(i)=omg0;
% Amplitude11(i)=sqrt(A(2)^2+A(4)^2);
% Amplitude12(i)=sqrt(A(3)^2+A(5)^2);
Amplitude(i)=sqrt(A(2)^2+A(1)^2+A(3)^2+A(4)^2);
Result_A2(:,i)=A;
i=i+1;
end
Result_A= [Result_A1,zeros(length(A),Num_Incremental_step-Num_Pre_step)]+ Result_A2;
% figure(1)
% plot(Frequency,Amplitude11,’o-‘,’linewidth’,2,’color’,’r’);
% xlabel(‘Frequency’);
% ylabel(‘Amplitude’);
% figure(2)
% plot(Frequency,Amplitude12,’o-‘,’linewidth’,2,’color’,’b’);
% xlabel(‘Frequency’);
% ylabel(‘Amplitude’);
figure(3)
plot(Frequency,Amplitude,’o-‘,’linewidth’,2,’color’,’b’);
xlabel(‘Frequency’);
ylabel(‘Amplitude’);
grid on
toc
Warning: The maximum function count has been exceeded; May have singularity. Hello everyone, I am a beginner in Matlab programming and have been trying to solve the differential equation system for incremental harmonic balance (IHB) given below. I have a MATLAB program, but there seems to be a problem and the analysis results are not satisfactory. We would greatly appreciate any assistance or related work. Thank you in advance.
matlab code
clear all
close all
clc
tic
syms t
%========输入基本参数(已知条件)======
%========duffing 方程得参数===========
a=0.95; %负刚度弹簧在静平衡位置的长度无量纲
lambda=0.085;
lambda_s=-4*lambda*(a-1)/(4*lambda*(a-1)+a);
miu=0.00001; %质量比
xi=0.05;%正刚度阻尼比
xi_b1=0.001;%负刚度装置阻尼比
z=0.06;%幅值
p0=-4*lambda*(1/(a^2)^(1/2)-1);
p1=(2*lambda)/(a^2)^(3/2);
p2=-(3*lambda)/(2*(a^2)^(5/2));
p3=(5*lambda)/(4*(a^2)^(7/2));
p4=-(35*lambda)/(32*(a^2)^(9/2));
p5=(63*lambda)/(64*(a^2)^(11/2));
m=[1,0;0,miu];% m惯性项系数
k=[1+lambda_s,-lambda_s;-lambda_s,lambda_s+p0];% k一次项系数
f=[z;0];% f激励幅值
c=[2*xi,0;0,2*xi_b1];% c阻尼系数
%=====控制参数
omg0=0.005;domg=0.0183;%频率比初始值与增量
%%%%%%能否收敛,delta_s和Nd的取值至关重要
%Nd一般要大于2,易收敛时Nd不宜太大,Nd越小,取值点越密集。非线性较强,Nd取值应稍大一些
delta_s=0.02;%弧长增量值
Nd=1;
Num_Pre_step=4; %预测解需要预测Num_Pre_step步
Num_Incremental_step=160; %程序总共计算Num_Incremental_step步
%========设置谐波矩阵=================
Cs=[ cos(t) sin(t) cos(2*t) sin(2*t)];
S=blkdiag(Cs,Cs);
S1=diff(S,t,1);
S2=diff(S,t,2);
%========设置A矩阵初值================
A1=[ 0.1 0.1 0.1 0.1];%上部结构位移响应的谐波系数
A2=[ 0.1 0.1 0.1 0.1];%调谐装置位移响应的谐波系数
A=[A1,A2]’;%傅里叶系数矩阵
length_A=length(A);
%========质量矩阵m====================
%========刚度矩阵k====================
%========阻尼矩阵k====================
%========外激励矩阵f==================
%========非线性刚度矩阵===============
A0=[zeros(1,length(A1)),A(1:length(A2),:)’]’;
q=(S*A0)’;
kn3=[0;p1]*q.^2;
kn5=[0;p2]*q.^4;
kn7=[0;p3]*q.^6;
kn9=[0;p4]*q.^8;
kn11=[0;p5]*q.^10;
%================
%========积分过程==
fm=inline(S’*m*S2);
M=quadv(fm,0,2*pi);%质量矩阵
fk=inline(S’*k*S);
K=quadv(fk,0,2*pi);%线性刚度矩阵
fc=inline(S’*c*S1);
C=quadv(fc,0,2*pi);%阻尼矩阵
fkn3=inline(S’*kn3*S);
KN3=quadv(fkn3,0,2*pi);%非线性矩阵
fkn5=inline(S’*kn5*S);
KN5=quadv(fkn5,0,2*pi);%非线性矩阵
fkn7=inline(S’*kn7*S);
KN7=quadv(fkn7,0,2*pi);%非线性矩阵
fkn9=inline(S’*kn9*S);
KN9=quadv(fkn9,0,2*pi);%非线性矩阵
fkn11=inline(S’*kn11*S);
KN11=quadv(fkn11,0,2*pi);%非线性矩阵
ff=inline(S’*f*cos(t));
F=quadv(ff,0,2*pi);%激励矩阵
%=========带入公式,公式推导可见陈的书
Kmc=omg0^2*M+omg0*C+K+3*KN3+5*KN5+7*KN7+9*KN9+11*KN11;
R=-F-(omg0^2*M+omg0*C+K+KN3+KN5+KN7+KN9+KN11)*A;
Rmc=-(2*omg0*M+C)*A;
Delta_A=inv(Kmc)*R;
%=======开始迭代过程
epsR=1e-4;
i=1;
X=zeros(length_A+1,4); %建立0矩阵便于保存四个解用于预测
s=zeros(1,3);
Harmonic_A=[]; %用于保存每一个解的谐波项系数
Result_A1=[ ];
for i=1:Num_Pre_step %该部分没有应用弧长法,预先求得一部分解便于弧长法的预测
n=1;tol=1;
while tol>epsR
A=A+Delta_A;
%====回代非线性刚度矩阵,计算下一次循环过程的非线性刚度矩阵
A0=[zeros(1,length(A1)),A(1:length(A2),:)’]’;
q=(S*A0)’;
kn3=[0;p1]*q.^2;
kn5=[0;p2]*q.^4;
kn7=[0;p3]*q.^6;
kn9=[0;p4]*q.^8;
kn11=[0;p5]*q.^10;
fkn3=inline(S’*kn3*S);
KN3=quadv(fkn3,0,2*pi);%非线性矩阵
fkn5=inline(S’*kn5*S);
KN5=quadv(fkn5,0,2*pi);%非线性矩阵
fkn7=inline(S’*kn7*S);
KN7=quadv(fkn7,0,2*pi);%非线性矩阵
fkn9=inline(S’*kn9*S);
KN9=quadv(fkn9,0,2*pi);%非线性矩阵
fkn11=inline(S’*kn11*S);
KN11=quadv(fkn11,0,2*pi);%非线性矩阵
%====再一次计算
Kmc=omg0^2*M+omg0*C+K+3*KN3+5*KN5+7*KN7+9*KN9+11*KN11;
R=-F-(omg0^2*M+omg0*C+K+KN3+KN5+KN7+KN9+KN11)*A;
Rmc=-(2*omg0*M+C)*A;
tol=norm(R);
Delta_A=inv(Kmc)*R;
if(n>60)
disp(‘迭代步数太多,可能不收敛’)
return
end
n=n+1;
end
I3=n-1;
disp([‘增量步=’ num2str(i),’ 迭代次数=’ num2str(I3),’ 本增量步弧长=’ num2str(delta_s),’ 已计算到频率=’ num2str(omg0)])
Harmonic_A=[Harmonic_A;A’];
%%%%%%%%%%%%%保存最新的四组解,便于弧长法预测
for p=1:3
X(:,p)=X(:,p+1);
end
X(1:length_A,4)=A;
X(length_A+1,4)=omg0;
p=0;
%%%%%%%%%%%%%
Frequency(i)=omg0;
% Amplitude11(i)=sqrt(A(2)^2+A(4)^2);
% Amplitude12(i)=sqrt(A(3)^2+A(5)^2);
Amplitude(i)=sqrt(A(2)^2+A(1)^2+A(3)^2+A(4)^2);
Result_A1(:,i)=A;
omg0=omg0+domg;
i=i+1;
end
% 以下是结合了弧长法的增量谐波平衡法
Result_A2=[];
for i=Num_Pre_step+1:Num_Incremental_step %%%%取Num_Incremental_step个增量步
n=1;tol=1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%
for kk=1:3
s(kk)=norm(X(:,kk+1)-X(:,kk));
end
tt(1)=0;tt(2)=s(1);tt(3)=tt(2)+s(2);tt(4)=tt(3)+s(3);tt(5)=tt(4)+delta_s;
PreValue_X=zeros(length_A+1,1);
for ii=1:4
aa=1;
for jj=1:4
if jj~=ii
aa=aa*((tt(5)-tt(jj))/(tt(ii)-tt(jj)));
end
end
PreValue_X=PreValue_X+aa*X(:,ii);
end
A=PreValue_X(1:length_A);
omg0=PreValue_X(length_A+1);
%%%%%%%%%%%%%%%%%%%%%%%%%% 以上这部分为弧长法,根据已经计算得到的四组解预测下一个解的过程,可见陈的书P177
%%%%%计算非线性刚度矩阵
A0=[zeros(1,length(A1)),A(1:length(A2),:)’]’;
q=(S*A0)’;
kn3=[0;p1]*q.^2;
kn5=[0;p2]*q.^4;
kn7=[0;p3]*q.^6;
kn9=[0;p4]*q.^8;
kn11=[0;p5]*q.^10;
fkn3=inline(S’*kn3*S);
KN3=quadv(fkn3,0,2*pi);%非线性矩阵
fkn5=inline(S’*kn5*S);
KN5=quadv(fkn5,0,2*pi);%非线性矩阵
fkn7=inline(S’*kn7*S);
KN7=quadv(fkn7,0,2*pi);%非线性矩阵
fkn9=inline(S’*kn9*S);
KN9=quadv(fkn9,0,2*pi);%非线性矩阵
fkn11=inline(S’*kn11*S);
KN11=quadv(fkn11,0,2*pi);%非线性矩阵
Kmc=omg0^2*M+omg0*C+K+3*KN3+5*KN5+7*KN7+9*KN9+11*KN11;
R=-F-(omg0^2*M+omg0*C+K+KN3+KN5+KN7+KN9+KN11)*A;
Rmc=-(2*omg0*M+C)*A;
%%%%%%%%%%%%判断并寻找控制变量
DELTA_X=PreValue_X-X(:,4); %DELTA_X是预测解与上一增量步的差值,只用来寻找最大值元素,与Delta_X的意义不同。Delta_X是每一个迭代步产生的插值
[~,flag]=max(abs(DELTA_X(1:length_A)));%找到绝对值最大的元素及其下标索引Note_flag,注意要把omg0排除在外,找delta_A中的最大值元素
Note_flag=flag;
%%%%%%%%%%%%%%%%%%%%处理求得的解,得到我们所需要的Delta_A和domg
Kmc(:,Note_flag)=-Rmc(:,1);
Kmc=Kmc(1:length_A,1:length_A);
Delta_X=inv(Kmc)*R;
Delta_X(length_A+1)=0;
Delta_X(length_A+1)=Delta_X(Note_flag);
Delta_X(Note_flag)=0;
Delta_A=Delta_X(1:length_A);
domg=Delta_X(length_A+1);
%A00=[w0;A0(2:6,1)];
A=A+Delta_A;
omg0=omg0+domg;
%%%%%%%%%%%%%%%%%%%%%%%%%下面是每个增量步内的循环迭代
while tol>epsR
%====回代非线性刚度矩阵,计算下一次循环过程的非线性刚度矩阵
A0=[zeros(1,length(A1)),A(1:length(A2),:)’]’;
q=(S*A0)’;
kn3=[0;p1]*q.^2;
kn5=[0;p2]*q.^4;
kn7=[0;p3]*q.^6;
kn9=[0;p4]*q.^8;
kn11=[0;p5]*q.^10;
fkn3=inline(S’*kn3*S);
KN3=quadv(fkn3,0,2*pi);%非线性矩阵
fkn5=inline(S’*kn5*S);
KN5=quadv(fkn5,0,2*pi);%非线性矩阵
fkn7=inline(S’*kn7*S);
KN7=quadv(fkn7,0,2*pi);%非线性矩阵
fkn9=inline(S’*kn9*S);
KN9=quadv(fkn9,0,2*pi);%非线性矩阵
fkn11=inline(S’*kn11*S);
KN11=quadv(fkn11,0,2*pi);%非线性矩阵
%%%%%%%%%%%%%%%%
Kmc=omg0^2*M+omg0*C+K+3*KN3+5*KN5+7*KN7+9*KN9+11*KN11;
R=-F-(omg0^2*M+omg0*C+K+KN3+KN5+KN7+KN9+KN11)*A;
Rmc=-(2*omg0*M+C)*A;
tol=norm(R);
Kmc(:,Note_flag)=-Rmc(:,1);
Kmc=Kmc(1:length_A,1:length_A);
Delta_X=inv(Kmc)*R;
Delta_X(length_A+1)=0;
Delta_X(length_A+1)=Delta_X(Note_flag);
Delta_X(Note_flag)=0;
Delta_A=Delta_X(1:length_A);
domg=Delta_X(length_A+1);
%A00=[w0;A0(2:6,1)];
A=A+Delta_A;
omg0=omg0+domg;
if(n>60)
disp(‘迭代步数太多,可能不收敛’)
return
end
n=n+1;
end
I3=n-1;
disp([‘增量步=’ num2str(i),’ 迭代次数=’ num2str(I3),’ 本增量步弧长=’ num2str(delta_s),’ 已计算到频率比=’ num2str(omg0)])
Harmonic_A=[Harmonic_A;A’];
delta_s=delta_s*Nd/I3;
% [i I3 delta_s omg0]
%%%%%%%%%%%%%保存最新的四组解,用于预测
for p=1:3
X(:,p)=X(:,p+1);
end
X(1:length_A,4)=A;
X(length_A+1,4)=omg0;
p=0;
%%%%%%%%%%%%%
Frequency(i)=omg0;
% Amplitude11(i)=sqrt(A(2)^2+A(4)^2);
% Amplitude12(i)=sqrt(A(3)^2+A(5)^2);
Amplitude(i)=sqrt(A(2)^2+A(1)^2+A(3)^2+A(4)^2);
Result_A2(:,i)=A;
i=i+1;
end
Result_A= [Result_A1,zeros(length(A),Num_Incremental_step-Num_Pre_step)]+ Result_A2;
% figure(1)
% plot(Frequency,Amplitude11,’o-‘,’linewidth’,2,’color’,’r’);
% xlabel(‘Frequency’);
% ylabel(‘Amplitude’);
% figure(2)
% plot(Frequency,Amplitude12,’o-‘,’linewidth’,2,’color’,’b’);
% xlabel(‘Frequency’);
% ylabel(‘Amplitude’);
figure(3)
plot(Frequency,Amplitude,’o-‘,’linewidth’,2,’color’,’b’);
xlabel(‘Frequency’);
ylabel(‘Amplitude’);
grid on
toc
Warning: The maximum function count has been exceeded; May have singularity. matlab ihb MATLAB Answers — New Questions
Digital Filter Design block error, filter not valid, please redesign.
I am using MATLAB R2025b and trying to design FIR filters using window function in Simulink using the Digital Filter Design Block, when I run the model it gives an error message box saying: "fliiter design is not valid. please redesign". I tried generating MATLAB code of the block and the code runs with no errors.
parameters I used:
low pass filter
rectangular window
order = 50
Fs = 48000 Hz
Fc = 10800 HzI am using MATLAB R2025b and trying to design FIR filters using window function in Simulink using the Digital Filter Design Block, when I run the model it gives an error message box saying: "fliiter design is not valid. please redesign". I tried generating MATLAB code of the block and the code runs with no errors.
parameters I used:
low pass filter
rectangular window
order = 50
Fs = 48000 Hz
Fc = 10800 Hz I am using MATLAB R2025b and trying to design FIR filters using window function in Simulink using the Digital Filter Design Block, when I run the model it gives an error message box saying: "fliiter design is not valid. please redesign". I tried generating MATLAB code of the block and the code runs with no errors.
parameters I used:
low pass filter
rectangular window
order = 50
Fs = 48000 Hz
Fc = 10800 Hz digital signal processing, digital filter design block MATLAB Answers — New Questions
Can “diary” be set to export exact text where hyperlinks are invoked instead of code or other characters?
The output of "diary" echoes what appears in the Command window, except for certain hyperlinks invoked by Matlab. Is there a way to echo literally what appears on the screen instead of code?
For example,
str = sprintf(‘%s%s’, …
‘<a href="matlab:magic(4)">’, …
‘Generate magic square</a>’);
disp(str)
MATLAB displays this in the Command Window:
However, the diary file, when viewed in a text editor, shows this text instead:
<a href="matlab:magic(4)">Generate magic square</a>
Thanks in advance…The output of "diary" echoes what appears in the Command window, except for certain hyperlinks invoked by Matlab. Is there a way to echo literally what appears on the screen instead of code?
For example,
str = sprintf(‘%s%s’, …
‘<a href="matlab:magic(4)">’, …
‘Generate magic square</a>’);
disp(str)
MATLAB displays this in the Command Window:
However, the diary file, when viewed in a text editor, shows this text instead:
<a href="matlab:magic(4)">Generate magic square</a>
Thanks in advance… The output of "diary" echoes what appears in the Command window, except for certain hyperlinks invoked by Matlab. Is there a way to echo literally what appears on the screen instead of code?
For example,
str = sprintf(‘%s%s’, …
‘<a href="matlab:magic(4)">’, …
‘Generate magic square</a>’);
disp(str)
MATLAB displays this in the Command Window:
However, the diary file, when viewed in a text editor, shows this text instead:
<a href="matlab:magic(4)">Generate magic square</a>
Thanks in advance… diary, literal text display, command window MATLAB Answers — New Questions
Why do newer Pixhawk Cube Orange+ boards fail to work with PX4 v1.14.x when using the UAV Toolbox Support Package for PX4 Autopilots?
Some users have reported that recently purchased Pixhawk Cube Orange+ boards exhibit compatibility issues with PX4 v1.14.x (as bundled in MATLAB R2024a–R2025b). While older Cube Orange+ units work correctly, newer boards show the following problems under PX4 v1.14.0 / v1.14.3:
PX4 boots with the error tune.
RC input is missing:
QGroundControl’s Radio setup shows no channels.
MAVLink Inspector shows no RC_CHANNELS / RC_CHANNELS_RAW messages.
SBUS RCIN is not recognized; enabling ELRS/CRSF only gives glitchy signals.
LiDAR (e.g., TFMini) stops publishing; no DISTANCE_SENSOR messages.
PWM_MAIN channels 1–8 appear disabled, and PWM_MAIN_TIM* parameters are missing.
Flashing PX4 v1.15+ resolves these issues, suggesting that newer Cube Orange+ hardware requires changes not present in PX4 v1.14.x.
Questions:
Is this a known issue with newer Cube Orange+ boards and PX4 v1.14.x?
Is there a roadmap to support PX4 v1.15+ in MATLAB PX4 Toolbox?
Is there any workaround to make these boards work with PX4 v1.14.x in MATLAB?Some users have reported that recently purchased Pixhawk Cube Orange+ boards exhibit compatibility issues with PX4 v1.14.x (as bundled in MATLAB R2024a–R2025b). While older Cube Orange+ units work correctly, newer boards show the following problems under PX4 v1.14.0 / v1.14.3:
PX4 boots with the error tune.
RC input is missing:
QGroundControl’s Radio setup shows no channels.
MAVLink Inspector shows no RC_CHANNELS / RC_CHANNELS_RAW messages.
SBUS RCIN is not recognized; enabling ELRS/CRSF only gives glitchy signals.
LiDAR (e.g., TFMini) stops publishing; no DISTANCE_SENSOR messages.
PWM_MAIN channels 1–8 appear disabled, and PWM_MAIN_TIM* parameters are missing.
Flashing PX4 v1.15+ resolves these issues, suggesting that newer Cube Orange+ hardware requires changes not present in PX4 v1.14.x.
Questions:
Is this a known issue with newer Cube Orange+ boards and PX4 v1.14.x?
Is there a roadmap to support PX4 v1.15+ in MATLAB PX4 Toolbox?
Is there any workaround to make these boards work with PX4 v1.14.x in MATLAB? Some users have reported that recently purchased Pixhawk Cube Orange+ boards exhibit compatibility issues with PX4 v1.14.x (as bundled in MATLAB R2024a–R2025b). While older Cube Orange+ units work correctly, newer boards show the following problems under PX4 v1.14.0 / v1.14.3:
PX4 boots with the error tune.
RC input is missing:
QGroundControl’s Radio setup shows no channels.
MAVLink Inspector shows no RC_CHANNELS / RC_CHANNELS_RAW messages.
SBUS RCIN is not recognized; enabling ELRS/CRSF only gives glitchy signals.
LiDAR (e.g., TFMini) stops publishing; no DISTANCE_SENSOR messages.
PWM_MAIN channels 1–8 appear disabled, and PWM_MAIN_TIM* parameters are missing.
Flashing PX4 v1.15+ resolves these issues, suggesting that newer Cube Orange+ hardware requires changes not present in PX4 v1.14.x.
Questions:
Is this a known issue with newer Cube Orange+ boards and PX4 v1.14.x?
Is there a roadmap to support PX4 v1.15+ in MATLAB PX4 Toolbox?
Is there any workaround to make these boards work with PX4 v1.14.x in MATLAB? px4 MATLAB Answers — New Questions
inability to open matkab on my laptop after installation
i installed matlab on my laptop(dell), but it did not open and with that, i could not be able to do anything at all, please help me on fixing it thanksi installed matlab on my laptop(dell), but it did not open and with that, i could not be able to do anything at all, please help me on fixing it thanks i installed matlab on my laptop(dell), but it did not open and with that, i could not be able to do anything at all, please help me on fixing it thanks un MATLAB Answers — New Questions
when I download the matlab R2024a simulink , it always display that occur abnormal condition please try to run the installation program again.
when I download the simulink , it always display that occur abnormal condition please try to run the installation program,my matlab versions is R2024a,and i am a undergraduate student ,I have the lisence , have the installation license. I have try to run as the administrator,and delate the file that its name have the “_temp_matlab_R20XXy_win64”, there also a information that i graduate as a undergraduate and changed the school email address ,I think it may be a question ,so I change the mathwork to graduate student email adress today,but it also can not install successful,how can i do.when I download the simulink , it always display that occur abnormal condition please try to run the installation program,my matlab versions is R2024a,and i am a undergraduate student ,I have the lisence , have the installation license. I have try to run as the administrator,and delate the file that its name have the “_temp_matlab_R20XXy_win64”, there also a information that i graduate as a undergraduate and changed the school email address ,I think it may be a question ,so I change the mathwork to graduate student email adress today,but it also can not install successful,how can i do. when I download the simulink , it always display that occur abnormal condition please try to run the installation program,my matlab versions is R2024a,and i am a undergraduate student ,I have the lisence , have the installation license. I have try to run as the administrator,and delate the file that its name have the “_temp_matlab_R20XXy_win64”, there also a information that i graduate as a undergraduate and changed the school email address ,I think it may be a question ,so I change the mathwork to graduate student email adress today,but it also can not install successful,how can i do. simulink download, matlab, toolboox MATLAB Answers — New Questions
I received the following error:
Warning: Executing startup failed in matlabrc.
This indicates a potentially serious problem in your MATLAB setup, which should be resolved as soon as possible. Error detected was:
MATLAB:calllib:MethodNotFound
Method was not found.Warning: Executing startup failed in matlabrc.
This indicates a potentially serious problem in your MATLAB setup, which should be resolved as soon as possible. Error detected was:
MATLAB:calllib:MethodNotFound
Method was not found. Warning: Executing startup failed in matlabrc.
This indicates a potentially serious problem in your MATLAB setup, which should be resolved as soon as possible. Error detected was:
MATLAB:calllib:MethodNotFound
Method was not found. matlabrc calllib methodnotfound MATLAB Answers — New Questions
how to draw voronoi cells of each vertex bounded inside an area and obtain the values of each of the cell areas independently?
how to draw voronoi cells of each vertex bounded inside an area and obtain the values of each of the cell areas independently?how to draw voronoi cells of each vertex bounded inside an area and obtain the values of each of the cell areas independently? how to draw voronoi cells of each vertex bounded inside an area and obtain the values of each of the cell areas independently? voronoi MATLAB Answers — New Questions
Help implementing 4th-order Runge–Kutta for ODEs with Dirac impulses (discontinuous system)
Hello everyone,
I am trying to reproduce the numerical results of a published tumour–immune ODE model that includes Dirac-type impulsive inputs. The system has four coupled variables [U,Y,Z,X][U, Y, Z, X][U,Y,Z,X]. Between injections, the dynamics are continuous, and at each injection time an instantaneous jump is applied to UUU:
Continuous part:
dU/dt = –kYU·U
dY/dt = kYU·U – kEY·Y
dZ/dt = kZY·Y – kEZ·Z
dX/dt = kX·X – kEX·X – η·Y·X·exp(–λ·Z)
At each dose time t=ti:
U(ti+)=U(ti−)+dosei×massi
I have implemented this in MATLAB using two scripts:
A main script, where I loop over the dose times, call ode45 between impulses, and apply the jump in UUU. For example:
% Mouse 1 parameters and initial conditions
y_curr = [M1.U0; M1.Y0; M1.Z0; M1.X0];
t_curr = M1.t0;
for i = 1:length(tDose1)
ti = tDose1(i);
if ti > M1.tend, break; end
% integrate continuously until next dose
[t_seg, Y_seg] = ode45(@(t,y) fM1_fun(t,y,M1), [t_curr ti], y_curr, options);
% store results (code omitted here)
if isempty(t_all1)
t_all1 = t_seg;
Y_all1 = Y_seg;
else
t_all1 = [t_all1; t_seg(2:end,:)];
Y_all1 = [Y_all1; Y_seg(2:end,:)];
end
% state just before the impulse
y_curr = Y_seg(end,:)’;
% apply Dirac-type impulse to U
Mi = mass_fun1(ti); % interpolated mass at ti
ui = uDose1(i); % dose at ti (mg/kg)
y_curr(1) = y_curr(1) + ui * Mi; % jump in U
t_curr = ti;
end
2. ODE function files, one for each parameter set (Mouse 1 and Mouse 2). For example, for Mouse 1:
function dydt = fM1_fun(t,y,M1)
dU = -M1.kYU * y(1);
dY = M1.kYU * y(1) – M1.kEY * y(2);
dZ = M1.kZY * y(2) – M1.kEZ * y(3);
dX = M1.kX * y(4) – M1.kEX * y(4) …
– M1.etaEY * y(2) .* y(4) .* exp(-M1.lambda * y(3));
dydt = [dU; dY; dZ; dX];
end
The code runs without errors and the qualitative behaviour is reasonable, but the resulting trajectories do not match the published figures, even though the ODEs, parameters, dose times, and mass values were reproduced as closely as possible from the article.
Since all variables depend on U(t), any mismatch in handling the discontinuities propagates through the entire system.
I am unsure whether the mismatch is due to solver handling of the discontinuities, or to something subtle in the way I am implementing the impulses.
I would really appreciate if someone could look at this structure and tell me if I am handling the Dirac-type impulses and the splitting of the integration in a correct way for ode45, or if there is anything obviously wrong or missing in this implementation that could explain why my simulated curves do not match the published plots.
Thank you in advance for any help or suggestions.Hello everyone,
I am trying to reproduce the numerical results of a published tumour–immune ODE model that includes Dirac-type impulsive inputs. The system has four coupled variables [U,Y,Z,X][U, Y, Z, X][U,Y,Z,X]. Between injections, the dynamics are continuous, and at each injection time an instantaneous jump is applied to UUU:
Continuous part:
dU/dt = –kYU·U
dY/dt = kYU·U – kEY·Y
dZ/dt = kZY·Y – kEZ·Z
dX/dt = kX·X – kEX·X – η·Y·X·exp(–λ·Z)
At each dose time t=ti:
U(ti+)=U(ti−)+dosei×massi
I have implemented this in MATLAB using two scripts:
A main script, where I loop over the dose times, call ode45 between impulses, and apply the jump in UUU. For example:
% Mouse 1 parameters and initial conditions
y_curr = [M1.U0; M1.Y0; M1.Z0; M1.X0];
t_curr = M1.t0;
for i = 1:length(tDose1)
ti = tDose1(i);
if ti > M1.tend, break; end
% integrate continuously until next dose
[t_seg, Y_seg] = ode45(@(t,y) fM1_fun(t,y,M1), [t_curr ti], y_curr, options);
% store results (code omitted here)
if isempty(t_all1)
t_all1 = t_seg;
Y_all1 = Y_seg;
else
t_all1 = [t_all1; t_seg(2:end,:)];
Y_all1 = [Y_all1; Y_seg(2:end,:)];
end
% state just before the impulse
y_curr = Y_seg(end,:)’;
% apply Dirac-type impulse to U
Mi = mass_fun1(ti); % interpolated mass at ti
ui = uDose1(i); % dose at ti (mg/kg)
y_curr(1) = y_curr(1) + ui * Mi; % jump in U
t_curr = ti;
end
2. ODE function files, one for each parameter set (Mouse 1 and Mouse 2). For example, for Mouse 1:
function dydt = fM1_fun(t,y,M1)
dU = -M1.kYU * y(1);
dY = M1.kYU * y(1) – M1.kEY * y(2);
dZ = M1.kZY * y(2) – M1.kEZ * y(3);
dX = M1.kX * y(4) – M1.kEX * y(4) …
– M1.etaEY * y(2) .* y(4) .* exp(-M1.lambda * y(3));
dydt = [dU; dY; dZ; dX];
end
The code runs without errors and the qualitative behaviour is reasonable, but the resulting trajectories do not match the published figures, even though the ODEs, parameters, dose times, and mass values were reproduced as closely as possible from the article.
Since all variables depend on U(t), any mismatch in handling the discontinuities propagates through the entire system.
I am unsure whether the mismatch is due to solver handling of the discontinuities, or to something subtle in the way I am implementing the impulses.
I would really appreciate if someone could look at this structure and tell me if I am handling the Dirac-type impulses and the splitting of the integration in a correct way for ode45, or if there is anything obviously wrong or missing in this implementation that could explain why my simulated curves do not match the published plots.
Thank you in advance for any help or suggestions. Hello everyone,
I am trying to reproduce the numerical results of a published tumour–immune ODE model that includes Dirac-type impulsive inputs. The system has four coupled variables [U,Y,Z,X][U, Y, Z, X][U,Y,Z,X]. Between injections, the dynamics are continuous, and at each injection time an instantaneous jump is applied to UUU:
Continuous part:
dU/dt = –kYU·U
dY/dt = kYU·U – kEY·Y
dZ/dt = kZY·Y – kEZ·Z
dX/dt = kX·X – kEX·X – η·Y·X·exp(–λ·Z)
At each dose time t=ti:
U(ti+)=U(ti−)+dosei×massi
I have implemented this in MATLAB using two scripts:
A main script, where I loop over the dose times, call ode45 between impulses, and apply the jump in UUU. For example:
% Mouse 1 parameters and initial conditions
y_curr = [M1.U0; M1.Y0; M1.Z0; M1.X0];
t_curr = M1.t0;
for i = 1:length(tDose1)
ti = tDose1(i);
if ti > M1.tend, break; end
% integrate continuously until next dose
[t_seg, Y_seg] = ode45(@(t,y) fM1_fun(t,y,M1), [t_curr ti], y_curr, options);
% store results (code omitted here)
if isempty(t_all1)
t_all1 = t_seg;
Y_all1 = Y_seg;
else
t_all1 = [t_all1; t_seg(2:end,:)];
Y_all1 = [Y_all1; Y_seg(2:end,:)];
end
% state just before the impulse
y_curr = Y_seg(end,:)’;
% apply Dirac-type impulse to U
Mi = mass_fun1(ti); % interpolated mass at ti
ui = uDose1(i); % dose at ti (mg/kg)
y_curr(1) = y_curr(1) + ui * Mi; % jump in U
t_curr = ti;
end
2. ODE function files, one for each parameter set (Mouse 1 and Mouse 2). For example, for Mouse 1:
function dydt = fM1_fun(t,y,M1)
dU = -M1.kYU * y(1);
dY = M1.kYU * y(1) – M1.kEY * y(2);
dZ = M1.kZY * y(2) – M1.kEZ * y(3);
dX = M1.kX * y(4) – M1.kEX * y(4) …
– M1.etaEY * y(2) .* y(4) .* exp(-M1.lambda * y(3));
dydt = [dU; dY; dZ; dX];
end
The code runs without errors and the qualitative behaviour is reasonable, but the resulting trajectories do not match the published figures, even though the ODEs, parameters, dose times, and mass values were reproduced as closely as possible from the article.
Since all variables depend on U(t), any mismatch in handling the discontinuities propagates through the entire system.
I am unsure whether the mismatch is due to solver handling of the discontinuities, or to something subtle in the way I am implementing the impulses.
I would really appreciate if someone could look at this structure and tell me if I am handling the Dirac-type impulses and the splitting of the integration in a correct way for ode45, or if there is anything obviously wrong or missing in this implementation that could explain why my simulated curves do not match the published plots.
Thank you in advance for any help or suggestions. #bioinformatic #ode #rungekutta #dirac MATLAB Answers — New Questions
Export setup style replacement
This question says that the Export Setup dialog has been deprecated:
https://www.mathworks.com/matlabcentral/answers/2178487-how-can-i-access-the-export-setup-dialog-for-modifying-figures-before-export-in-matlab-r2025a
Over the years I have built up a library of export setup styles customized for different journal and conference settings (figure sizes, font sizes, resolution, line widths, etc). This has been an essential part of my workflow, allowing me to consistently reproduce figures for different targets without manual tweaking. The suggested replacement, uiexportdlg does not have the same granularity of control, nor the ability to save profiles. Is there an alternative that is closer to Export Setup capabilities?This question says that the Export Setup dialog has been deprecated:
https://www.mathworks.com/matlabcentral/answers/2178487-how-can-i-access-the-export-setup-dialog-for-modifying-figures-before-export-in-matlab-r2025a
Over the years I have built up a library of export setup styles customized for different journal and conference settings (figure sizes, font sizes, resolution, line widths, etc). This has been an essential part of my workflow, allowing me to consistently reproduce figures for different targets without manual tweaking. The suggested replacement, uiexportdlg does not have the same granularity of control, nor the ability to save profiles. Is there an alternative that is closer to Export Setup capabilities? This question says that the Export Setup dialog has been deprecated:
https://www.mathworks.com/matlabcentral/answers/2178487-how-can-i-access-the-export-setup-dialog-for-modifying-figures-before-export-in-matlab-r2025a
Over the years I have built up a library of export setup styles customized for different journal and conference settings (figure sizes, font sizes, resolution, line widths, etc). This has been an essential part of my workflow, allowing me to consistently reproduce figures for different targets without manual tweaking. The suggested replacement, uiexportdlg does not have the same granularity of control, nor the ability to save profiles. Is there an alternative that is closer to Export Setup capabilities? uiexportdlg, exportsetupdlg MATLAB Answers — New Questions
im facing problem in sepaarte touching objects
import cv2
import numpy as np
import os
output_folder = r"E:grains_output"
# Create the folder if it doesn’t exist
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Example: saving an image
img = cv2.imread(r"C:UsersDixuDownloadstest1.png") # your grain image
if img is None:
print("Error: Image not found! Check the path and filename.")
exit()
else:
print("Image loaded successfully!")
cv2.imwrite(os.path.join(output_folder, "segmented.png"), img)
# FUNCTION: Separate grains using COLOR segmentation (HSV
def separate_grains(image_path):
print("Loading:", image_path)
img = cv2.imread(image_path)
if img is None:
print("Error: image not found!")
return None, None
# Convert to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Yellow grains range
lower = np.array([15, 40, 60])
upper = np.array([40, 255, 255])
# Mask grains
mask = cv2.inRange(hsv, lower, upper)
# Morphology cleanup
kernel = np.ones((5, 5), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=3)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=2)
# Convert mask to binary
ret, thresh = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY)
# Noise removal
kernel = np.ones((3, 3), np.uint8)
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
# Sure background area
sure_bg = cv2.dilate(opening, kernel, iterations=3)
# Sure foreground area
dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2, 5)
ret, sure_fg = cv2.threshold(dist_transform, 0.6 * dist_transform.max(), 255, 0)
# Unknown region
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg, sure_fg)
# Marker labeling
ret, markers = cv2.connectedComponents(sure_fg)
markers = markers + 1 # background = 1
markers[unknown == 255] = 0
# Apply watershed
markers = cv2.watershed(img, markers)
mask[markers == -1] = 0 # boundaries
return mask, img
def save_grains(mask, img):
# print("Saving grains…")
output_dir = output_folder # Use the folder defined at the top
os.makedirs(output_dir, exist_ok=True)
# Find contours
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
grain_id = 1
for cnt in contours:
x, y, w, h = cv2.boundingRect(cnt)
if w < 10 or h < 10:
continue
grain = img[y:y + h, x:x + w]
filename = os.path.join(output_dir, f"grain_{grain_id}.png")
cv2.imwrite(filename, grain)
print("Saved:", filename)
grain_id += 1
print("nAll grains saved inside folder:", output_dir)
# Draw contours on a copy of the original image
result = img.copy()
cv2.drawContours(result, contours, -1, (0, 0, 255), 2)
# Save the segmented image
segmented_path = os.path.join(output_dir, "segmented_contours.png")
cv2.imwrite(segmented_path, result)
print("Segmented image with contours saved as:", segmented_path)
return result
# ———————————————————
# MAIN EXECUTION
# ———————————————————
if __name__ == "__main__":
# print("Current working directory:", os.getcwd())
mask, img = separate_grains(r"C:UsersDixuDownloadstest1.png")
if mask is not None:
result_img = save_grains(mask, img)
# # Show results
# cv2.namedWindow("Mask", cv2.WINDOW_NORMAL)
# cv2.resizeWindow("Mask", 600, 500)
# cv2.imshow("Mask", mask)
cv2.namedWindow("Segmented Image", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Segmented Image", 600, 500)
cv2.imshow("Segmented Image", result_img)
cv2.waitKey(0)
cv2.destroyAllWindows()import cv2
import numpy as np
import os
output_folder = r"E:grains_output"
# Create the folder if it doesn’t exist
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Example: saving an image
img = cv2.imread(r"C:UsersDixuDownloadstest1.png") # your grain image
if img is None:
print("Error: Image not found! Check the path and filename.")
exit()
else:
print("Image loaded successfully!")
cv2.imwrite(os.path.join(output_folder, "segmented.png"), img)
# FUNCTION: Separate grains using COLOR segmentation (HSV
def separate_grains(image_path):
print("Loading:", image_path)
img = cv2.imread(image_path)
if img is None:
print("Error: image not found!")
return None, None
# Convert to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Yellow grains range
lower = np.array([15, 40, 60])
upper = np.array([40, 255, 255])
# Mask grains
mask = cv2.inRange(hsv, lower, upper)
# Morphology cleanup
kernel = np.ones((5, 5), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=3)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=2)
# Convert mask to binary
ret, thresh = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY)
# Noise removal
kernel = np.ones((3, 3), np.uint8)
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
# Sure background area
sure_bg = cv2.dilate(opening, kernel, iterations=3)
# Sure foreground area
dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2, 5)
ret, sure_fg = cv2.threshold(dist_transform, 0.6 * dist_transform.max(), 255, 0)
# Unknown region
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg, sure_fg)
# Marker labeling
ret, markers = cv2.connectedComponents(sure_fg)
markers = markers + 1 # background = 1
markers[unknown == 255] = 0
# Apply watershed
markers = cv2.watershed(img, markers)
mask[markers == -1] = 0 # boundaries
return mask, img
def save_grains(mask, img):
# print("Saving grains…")
output_dir = output_folder # Use the folder defined at the top
os.makedirs(output_dir, exist_ok=True)
# Find contours
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
grain_id = 1
for cnt in contours:
x, y, w, h = cv2.boundingRect(cnt)
if w < 10 or h < 10:
continue
grain = img[y:y + h, x:x + w]
filename = os.path.join(output_dir, f"grain_{grain_id}.png")
cv2.imwrite(filename, grain)
print("Saved:", filename)
grain_id += 1
print("nAll grains saved inside folder:", output_dir)
# Draw contours on a copy of the original image
result = img.copy()
cv2.drawContours(result, contours, -1, (0, 0, 255), 2)
# Save the segmented image
segmented_path = os.path.join(output_dir, "segmented_contours.png")
cv2.imwrite(segmented_path, result)
print("Segmented image with contours saved as:", segmented_path)
return result
# ———————————————————
# MAIN EXECUTION
# ———————————————————
if __name__ == "__main__":
# print("Current working directory:", os.getcwd())
mask, img = separate_grains(r"C:UsersDixuDownloadstest1.png")
if mask is not None:
result_img = save_grains(mask, img)
# # Show results
# cv2.namedWindow("Mask", cv2.WINDOW_NORMAL)
# cv2.resizeWindow("Mask", 600, 500)
# cv2.imshow("Mask", mask)
cv2.namedWindow("Segmented Image", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Segmented Image", 600, 500)
cv2.imshow("Segmented Image", result_img)
cv2.waitKey(0)
cv2.destroyAllWindows() import cv2
import numpy as np
import os
output_folder = r"E:grains_output"
# Create the folder if it doesn’t exist
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Example: saving an image
img = cv2.imread(r"C:UsersDixuDownloadstest1.png") # your grain image
if img is None:
print("Error: Image not found! Check the path and filename.")
exit()
else:
print("Image loaded successfully!")
cv2.imwrite(os.path.join(output_folder, "segmented.png"), img)
# FUNCTION: Separate grains using COLOR segmentation (HSV
def separate_grains(image_path):
print("Loading:", image_path)
img = cv2.imread(image_path)
if img is None:
print("Error: image not found!")
return None, None
# Convert to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Yellow grains range
lower = np.array([15, 40, 60])
upper = np.array([40, 255, 255])
# Mask grains
mask = cv2.inRange(hsv, lower, upper)
# Morphology cleanup
kernel = np.ones((5, 5), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=3)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=2)
# Convert mask to binary
ret, thresh = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY)
# Noise removal
kernel = np.ones((3, 3), np.uint8)
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
# Sure background area
sure_bg = cv2.dilate(opening, kernel, iterations=3)
# Sure foreground area
dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2, 5)
ret, sure_fg = cv2.threshold(dist_transform, 0.6 * dist_transform.max(), 255, 0)
# Unknown region
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg, sure_fg)
# Marker labeling
ret, markers = cv2.connectedComponents(sure_fg)
markers = markers + 1 # background = 1
markers[unknown == 255] = 0
# Apply watershed
markers = cv2.watershed(img, markers)
mask[markers == -1] = 0 # boundaries
return mask, img
def save_grains(mask, img):
# print("Saving grains…")
output_dir = output_folder # Use the folder defined at the top
os.makedirs(output_dir, exist_ok=True)
# Find contours
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
grain_id = 1
for cnt in contours:
x, y, w, h = cv2.boundingRect(cnt)
if w < 10 or h < 10:
continue
grain = img[y:y + h, x:x + w]
filename = os.path.join(output_dir, f"grain_{grain_id}.png")
cv2.imwrite(filename, grain)
print("Saved:", filename)
grain_id += 1
print("nAll grains saved inside folder:", output_dir)
# Draw contours on a copy of the original image
result = img.copy()
cv2.drawContours(result, contours, -1, (0, 0, 255), 2)
# Save the segmented image
segmented_path = os.path.join(output_dir, "segmented_contours.png")
cv2.imwrite(segmented_path, result)
print("Segmented image with contours saved as:", segmented_path)
return result
# ———————————————————
# MAIN EXECUTION
# ———————————————————
if __name__ == "__main__":
# print("Current working directory:", os.getcwd())
mask, img = separate_grains(r"C:UsersDixuDownloadstest1.png")
if mask is not None:
result_img = save_grains(mask, img)
# # Show results
# cv2.namedWindow("Mask", cv2.WINDOW_NORMAL)
# cv2.resizeWindow("Mask", 600, 500)
# cv2.imshow("Mask", mask)
cv2.namedWindow("Segmented Image", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Segmented Image", 600, 500)
cv2.imshow("Segmented Image", result_img)
cv2.waitKey(0)
cv2.destroyAllWindows() python, cv2, image processing, image segmentation MATLAB Answers — New Questions
How can I use the AMD Optimizing CPU Libraries (AOCL) with MATLAB for windows?
My CPU is amd 9900X3D, GPU is RTX5070, Windows11 25H2
To use the AMD optimization in MATLAB, I have already see the Q&A for this link:’How can I use the BLAS and LAPACK implementations included in AMD Optimizing CPU Libraries (AOCL) with MATLAB R2022a? – MATLAB Answers – MATLAB Central’
Then I install the AOCL5.0 in this link:’AMD Optimizing CPU Libraries EULA 5.1′
Follow the tutorial in the text,I found matlab error:
———————————————————————————————–
version -blas, version -lapack
BLAS: trying environment BLAS_VERSION…
BLAS: loading AOCL-LibBlis-Win-MT-dll.dll
BLAS: unloading libraries
错误使用 matlab.lang.internal.versionPlugins.blas
BLAS 加载错误:
AOCL-LibBlis-Win-MT-dll.dll: 找不到指定的模块。
————————————————————–
Is this because my OS is Windows? and how to solve it?
Thank uMy CPU is amd 9900X3D, GPU is RTX5070, Windows11 25H2
To use the AMD optimization in MATLAB, I have already see the Q&A for this link:’How can I use the BLAS and LAPACK implementations included in AMD Optimizing CPU Libraries (AOCL) with MATLAB R2022a? – MATLAB Answers – MATLAB Central’
Then I install the AOCL5.0 in this link:’AMD Optimizing CPU Libraries EULA 5.1′
Follow the tutorial in the text,I found matlab error:
———————————————————————————————–
version -blas, version -lapack
BLAS: trying environment BLAS_VERSION…
BLAS: loading AOCL-LibBlis-Win-MT-dll.dll
BLAS: unloading libraries
错误使用 matlab.lang.internal.versionPlugins.blas
BLAS 加载错误:
AOCL-LibBlis-Win-MT-dll.dll: 找不到指定的模块。
————————————————————–
Is this because my OS is Windows? and how to solve it?
Thank u My CPU is amd 9900X3D, GPU is RTX5070, Windows11 25H2
To use the AMD optimization in MATLAB, I have already see the Q&A for this link:’How can I use the BLAS and LAPACK implementations included in AMD Optimizing CPU Libraries (AOCL) with MATLAB R2022a? – MATLAB Answers – MATLAB Central’
Then I install the AOCL5.0 in this link:’AMD Optimizing CPU Libraries EULA 5.1′
Follow the tutorial in the text,I found matlab error:
———————————————————————————————–
version -blas, version -lapack
BLAS: trying environment BLAS_VERSION…
BLAS: loading AOCL-LibBlis-Win-MT-dll.dll
BLAS: unloading libraries
错误使用 matlab.lang.internal.versionPlugins.blas
BLAS 加载错误:
AOCL-LibBlis-Win-MT-dll.dll: 找不到指定的模块。
————————————————————–
Is this because my OS is Windows? and how to solve it?
Thank u amd, matlab, acol MATLAB Answers — New Questions
“Unable to update data tip using custom update function”
Hey guys, when I make the custom text function for dataCursorMode it keeps on showing this when clicking on the marker on the plot
Here is the code for the plot
function WinChampgraph_team_selector
data2 = readtable("alltimeteams.xlsx",’VariableNamingRule’,’preserve’);
% Calculate the win percentage for each team
winPercent = (data2.Wins ./ (data2.Wins + data2.Losses));
hold on
graph = plot(winPercent, data2.Championships,"LineStyle","none","Color","r","Marker","*");
dcm = datacursormode;
dcm.Enable = ‘on’;
dcm.UpdateFcn = @displayteam;
getCursorInfo(dcm);
displayteam(data2);
xlabel(‘Win Percentage’);
ylabel(‘Championships’);
title(‘Team performance since the beginning of the NBA’);
grid on;
set(gcf,’Position’,[50,500,700,500])
end
Here is the code for the custom text function
function txt = displayteam(data3)
x = data3.Franchise;
y = (data3.Wins ./ (data3.Wins + data3.Losses));
myDatatipText = "(%s, %s, %s)";
txt = sprintf(myDatatipText, string(x), string(y),data3.Championships);
end
Then it shows this on the plot
Unable to update data tip using custom update function
Please lmk is anything else is neededHey guys, when I make the custom text function for dataCursorMode it keeps on showing this when clicking on the marker on the plot
Here is the code for the plot
function WinChampgraph_team_selector
data2 = readtable("alltimeteams.xlsx",’VariableNamingRule’,’preserve’);
% Calculate the win percentage for each team
winPercent = (data2.Wins ./ (data2.Wins + data2.Losses));
hold on
graph = plot(winPercent, data2.Championships,"LineStyle","none","Color","r","Marker","*");
dcm = datacursormode;
dcm.Enable = ‘on’;
dcm.UpdateFcn = @displayteam;
getCursorInfo(dcm);
displayteam(data2);
xlabel(‘Win Percentage’);
ylabel(‘Championships’);
title(‘Team performance since the beginning of the NBA’);
grid on;
set(gcf,’Position’,[50,500,700,500])
end
Here is the code for the custom text function
function txt = displayteam(data3)
x = data3.Franchise;
y = (data3.Wins ./ (data3.Wins + data3.Losses));
myDatatipText = "(%s, %s, %s)";
txt = sprintf(myDatatipText, string(x), string(y),data3.Championships);
end
Then it shows this on the plot
Unable to update data tip using custom update function
Please lmk is anything else is needed Hey guys, when I make the custom text function for dataCursorMode it keeps on showing this when clicking on the marker on the plot
Here is the code for the plot
function WinChampgraph_team_selector
data2 = readtable("alltimeteams.xlsx",’VariableNamingRule’,’preserve’);
% Calculate the win percentage for each team
winPercent = (data2.Wins ./ (data2.Wins + data2.Losses));
hold on
graph = plot(winPercent, data2.Championships,"LineStyle","none","Color","r","Marker","*");
dcm = datacursormode;
dcm.Enable = ‘on’;
dcm.UpdateFcn = @displayteam;
getCursorInfo(dcm);
displayteam(data2);
xlabel(‘Win Percentage’);
ylabel(‘Championships’);
title(‘Team performance since the beginning of the NBA’);
grid on;
set(gcf,’Position’,[50,500,700,500])
end
Here is the code for the custom text function
function txt = displayteam(data3)
x = data3.Franchise;
y = (data3.Wins ./ (data3.Wins + data3.Losses));
myDatatipText = "(%s, %s, %s)";
txt = sprintf(myDatatipText, string(x), string(y),data3.Championships);
end
Then it shows this on the plot
Unable to update data tip using custom update function
Please lmk is anything else is needed plot MATLAB Answers — New Questions
Difference in initial predicition for LSTM Training matlab
I have done timeseries training with LSTM in matlab. Once i am doing prediction for data apart from training i am observing difference in initial timestep then its matching quite well with actual test data. Is there any way to improve it?
Dataset has two input and one output. i have normalised dataset and havent considered time as feature in the dataset.I have done timeseries training with LSTM in matlab. Once i am doing prediction for data apart from training i am observing difference in initial timestep then its matching quite well with actual test data. Is there any way to improve it?
Dataset has two input and one output. i have normalised dataset and havent considered time as feature in the dataset. I have done timeseries training with LSTM in matlab. Once i am doing prediction for data apart from training i am observing difference in initial timestep then its matching quite well with actual test data. Is there any way to improve it?
Dataset has two input and one output. i have normalised dataset and havent considered time as feature in the dataset. deep learning, lstm MATLAB Answers — New Questions
The 3-Phase Inverter with PWM generation built using Matlab-Simulink, the output current is not same in all 3 Phases
Hello Community,
I generally work on 3D simulation tools associated with domains such as Powertrain NVH studies and I am new to Matlab-Simulink tools.
Now I am exploring the electrical/electronics domain (beginner) to get some initial data that will be required for further NVH studies.
I have made a 3-Phase Inverter with Pulse Width Modulation (PWM) circuit with help of tutorials online.
Currently I am facing this issue, where the output current extracted from the 3 Phase Inverter is not having the same magnitude(values) in
3 phases, How to correct the Matlab-simulink model regarding this issue?
Inputs given to the model,
DC Voltage source – 400 V
and Reference Sine wave blocks – Frequency 50Hz and Phase difference of 120 for 3 phases (Amplitude 1)
and carrier wave (Sawtooth generator) – Frequency 10,000 Hz (Amplitude 1)
The Load – 3-Phase Parallel RLC Branch – Only Resistor type is used with 1 Ohm resistance
Note: Regarding the grounding, two approaches I have tried – Grounding the load (RLC) and grounding the Inverter 6-switches loop (both have same results)
Thank you in advance for all the support and helpHello Community,
I generally work on 3D simulation tools associated with domains such as Powertrain NVH studies and I am new to Matlab-Simulink tools.
Now I am exploring the electrical/electronics domain (beginner) to get some initial data that will be required for further NVH studies.
I have made a 3-Phase Inverter with Pulse Width Modulation (PWM) circuit with help of tutorials online.
Currently I am facing this issue, where the output current extracted from the 3 Phase Inverter is not having the same magnitude(values) in
3 phases, How to correct the Matlab-simulink model regarding this issue?
Inputs given to the model,
DC Voltage source – 400 V
and Reference Sine wave blocks – Frequency 50Hz and Phase difference of 120 for 3 phases (Amplitude 1)
and carrier wave (Sawtooth generator) – Frequency 10,000 Hz (Amplitude 1)
The Load – 3-Phase Parallel RLC Branch – Only Resistor type is used with 1 Ohm resistance
Note: Regarding the grounding, two approaches I have tried – Grounding the load (RLC) and grounding the Inverter 6-switches loop (both have same results)
Thank you in advance for all the support and help Hello Community,
I generally work on 3D simulation tools associated with domains such as Powertrain NVH studies and I am new to Matlab-Simulink tools.
Now I am exploring the electrical/electronics domain (beginner) to get some initial data that will be required for further NVH studies.
I have made a 3-Phase Inverter with Pulse Width Modulation (PWM) circuit with help of tutorials online.
Currently I am facing this issue, where the output current extracted from the 3 Phase Inverter is not having the same magnitude(values) in
3 phases, How to correct the Matlab-simulink model regarding this issue?
Inputs given to the model,
DC Voltage source – 400 V
and Reference Sine wave blocks – Frequency 50Hz and Phase difference of 120 for 3 phases (Amplitude 1)
and carrier wave (Sawtooth generator) – Frequency 10,000 Hz (Amplitude 1)
The Load – 3-Phase Parallel RLC Branch – Only Resistor type is used with 1 Ohm resistance
Note: Regarding the grounding, two approaches I have tried – Grounding the load (RLC) and grounding the Inverter 6-switches loop (both have same results)
Thank you in advance for all the support and help three-phase inverters, pulse width modulation (pwm), simulink MATLAB Answers — New Questions
Closing the Property Inspector in R2025b
The Property Inspector pane does not appear to have a ‘Close’ button in R2025b, nor does its sidebar icon appear to have a dropdown selection to close, unlike most other sidebar icons. Why is that? How is it intended for the Property Inspector to be closed?The Property Inspector pane does not appear to have a ‘Close’ button in R2025b, nor does its sidebar icon appear to have a dropdown selection to close, unlike most other sidebar icons. Why is that? How is it intended for the Property Inspector to be closed? The Property Inspector pane does not appear to have a ‘Close’ button in R2025b, nor does its sidebar icon appear to have a dropdown selection to close, unlike most other sidebar icons. Why is that? How is it intended for the Property Inspector to be closed? graphics, property inpsector MATLAB Answers — New Questions
Pinning the AxesToolbar (revisited)
The AxesToolbar was introduced about 6 years ago,
However, I never embraced it, because it was not possible (at least not at the time) to pin the toolbar so that the exploration buttons are perpetually in view. A pinned view of the buttons is something I prefer from the days when the buttons were on the figure toolbar, though I do see the logic of tying the buttons to an axes, rather than a figure.
I thought I would check back in and see if this pinning capability now exists. I seem to remember I was not the only one calling for this feature. So is there now a way to make the AxesToolbar perpetually visible, even when the mouse is not hovering over the axes?The AxesToolbar was introduced about 6 years ago,
However, I never embraced it, because it was not possible (at least not at the time) to pin the toolbar so that the exploration buttons are perpetually in view. A pinned view of the buttons is something I prefer from the days when the buttons were on the figure toolbar, though I do see the logic of tying the buttons to an axes, rather than a figure.
I thought I would check back in and see if this pinning capability now exists. I seem to remember I was not the only one calling for this feature. So is there now a way to make the AxesToolbar perpetually visible, even when the mouse is not hovering over the axes? The AxesToolbar was introduced about 6 years ago,
However, I never embraced it, because it was not possible (at least not at the time) to pin the toolbar so that the exploration buttons are perpetually in view. A pinned view of the buttons is something I prefer from the days when the buttons were on the figure toolbar, though I do see the logic of tying the buttons to an axes, rather than a figure.
I thought I would check back in and see if this pinning capability now exists. I seem to remember I was not the only one calling for this feature. So is there now a way to make the AxesToolbar perpetually visible, even when the mouse is not hovering over the axes? axestoolbar, navigation, exploration, graphics, axes, plots, axtoolbar MATLAB Answers — New Questions
using knob to adjust audio frequency
How can I use a knob to adjust the frequency of audio such as the handel.mat soundHow can I use a knob to adjust the frequency of audio such as the handel.mat sound How can I use a knob to adjust the frequency of audio such as the handel.mat sound appdesigner, knob, audio MATLAB Answers — New Questions









