Category: Matlab
Category Archives: Matlab
How to get the y-axis in the foreground while having the grids in the background?
Dear all,
this is a version of my code:
figure()
hold on
grid on
set(gca, ‘Layer’, ‘top’)
jbfill(1:100,x(:,1)’,y(:,1)’,color.red, color.red,0,1);
hold off
xticks(0:1:100);
title(‘Temperature’);
ylabel(‘Percent’);
xlabel(‘Months’);
I have the following problem:
I try to get the grids in the background behind jbfill and the yaxis/ yticks above the jbfill, but jbfill is lying above the y-axis / y ticks and thus covering y-axis / y ticks. So in order to get the y-axis / y ticks above jbfill (to make them visible) I use " set (gca, ‘Layer’,’top’) " . But then the grids are automatically "above" jbfill although they should be not visible where the jbfill plot is.
Does someone have a hint how I can solve this problem?
Many thanks for your help!Dear all,
this is a version of my code:
figure()
hold on
grid on
set(gca, ‘Layer’, ‘top’)
jbfill(1:100,x(:,1)’,y(:,1)’,color.red, color.red,0,1);
hold off
xticks(0:1:100);
title(‘Temperature’);
ylabel(‘Percent’);
xlabel(‘Months’);
I have the following problem:
I try to get the grids in the background behind jbfill and the yaxis/ yticks above the jbfill, but jbfill is lying above the y-axis / y ticks and thus covering y-axis / y ticks. So in order to get the y-axis / y ticks above jbfill (to make them visible) I use " set (gca, ‘Layer’,’top’) " . But then the grids are automatically "above" jbfill although they should be not visible where the jbfill plot is.
Does someone have a hint how I can solve this problem?
Many thanks for your help! Dear all,
this is a version of my code:
figure()
hold on
grid on
set(gca, ‘Layer’, ‘top’)
jbfill(1:100,x(:,1)’,y(:,1)’,color.red, color.red,0,1);
hold off
xticks(0:1:100);
title(‘Temperature’);
ylabel(‘Percent’);
xlabel(‘Months’);
I have the following problem:
I try to get the grids in the background behind jbfill and the yaxis/ yticks above the jbfill, but jbfill is lying above the y-axis / y ticks and thus covering y-axis / y ticks. So in order to get the y-axis / y ticks above jbfill (to make them visible) I use " set (gca, ‘Layer’,’top’) " . But then the grids are automatically "above" jbfill although they should be not visible where the jbfill plot is.
Does someone have a hint how I can solve this problem?
Many thanks for your help! jbfill, axis, ‘layer’, grids, grid on MATLAB Answers — New Questions
Derivative of state ‘1’ in block ‘F16_Aircraft_MODEL/6DOF (Euler Angles)/p,q,r ‘ at time 0.0 is not finite. The simulation will be stopped.
Please help.Please help. Please help. aircraft modeling MATLAB Answers — New Questions
How can I solve the error: (linprog): Length of lower bounds l is too long; ignoring extra bounds
P_t_pv = ones(1, 24);
P_tmin_pv = ones(1, 24);
P_t_el = ones(1, 24);
P_t_hl = ones(1, 24);
P_tmin_cl = ones(1, 24);
P_tmax_cl = ones(1, 24);
P_t_net5 = optimvar("P_t_net",1,24,"LowerBound",0);
P_gt_CHP5 = optimvar("P_gt_CHP",1,24,"LowerBound",0);
P_t_cha5 = optimvar("P_t_cha",1,24,"LowerBound",0,"UpperBound",50);
P_t_dis5 = optimvar("P_t_dis",1,24,"LowerBound",0,"UpperBound",50);
u_t_cha5 = optimvar("u_t_cha",1,24,"Type","integer","LowerBound",0,…
"UpperBound",1);
u_t_dis5 = optimvar("u_t_dis",1,24,"Type","integer","LowerBound",0,…
"UpperBound",1);
P_et_EB5 = optimvar("P_et_EB",1,24,"LowerBound",0);
P_et_EC5 = optimvar("P_et_EC",1,24,"LowerBound",0);
P_ht_AC5 = optimvar("P_ht_AC",1,24,"LowerBound",0);
P_gt_GB5 = optimvar("P_gt_GB",1,24,"LowerBound",0);
E_t_f5 = optimvar("E_t_f",1,24,"LowerBound",0);
dP_t_pv5 = optimvar("dP_t_pv",1,24,"LowerBound",0);
dP_t_el5 = optimvar("dP_t_el",1,24,"LowerBound",0);
dP_t_hl5 = optimvar("dP_t_hl",1,24,"LowerBound",0);
dP_t_cl5 = optimvar("dP_t_cl",1,24,"LowerBound",0);
% 设置求解器的初始起点
initialPoint5.P_t_net = zeros(size(P_t_net5));
initialPoint5.P_gt_CHP = zeros(size(P_gt_CHP5));
initialPoint5.P_t_cha = zeros(size(P_t_cha5));
initialPoint5.P_t_dis = zeros(size(P_t_dis5));
initialPoint5.u_t_cha = zeros(size(u_t_cha5));
initialPoint5.u_t_dis = zeros(size(u_t_dis5));
initialPoint5.P_et_EB = zeros(size(P_et_EB5));
initialPoint5.P_et_EC = zeros(size(P_et_EC5));
initialPoint5.P_ht_AC = zeros(size(P_ht_AC5));
initialPoint5.P_gt_GB = zeros(size(P_gt_GB5));
initialPoint5.E_t_f = zeros(size(E_t_f5));
initialPoint5.dP_t_pv = zeros(size(dP_t_pv5));
initialPoint5.dP_t_el = zeros(size(dP_t_el5));
initialPoint5.dP_t_hl = zeros(size(dP_t_hl5));
initialPoint5.dP_t_cl = zeros(size(dP_t_cl5));
% 创建问题
problem = optimproblem;
% 定义问题目标
problem.Objective = fcn2optimexpr(@objectiveFcn,P_t_net5,P_gt_CHP5,P_t_cha5,…
P_et_EB5,P_et_EC5,P_ht_AC5,P_gt_GB5,E_t_f5,dP_t_pv5,dP_t_el5,dP_t_hl5,dP_t_cl5);
% 定义问题约束
problem.Constraints.constraint1 = P_t_net5+0.38*P_gt_CHP5+P_t_pv-dP_t_pv5 == P_t_el-dP_t_el5+P_et_EB5+P_et_EC5+P_t_cha5;
problem.Constraints.constraint2 = P_gt_CHP5*0.45+P_gt_GB5*0.95+P_et_EB5*0.98 == P_t_hl+P_ht_AC5-dP_t_hl5;
problem.Constraints.constraint3 = P_ht_AC5*1.1+P_et_EC5*3.1 >= P_tmin_cl-dP_t_cl5;
problem.Constraints.constraint4 = P_ht_AC5*1.1+P_et_EC5*3.1 <= P_tmax_cl;
problem.Constraints.constraint5 = 0.38*P_gt_CHP5 <= 300 * ones(1, 24);
problem.Constraints.constraint6 = (circshift(P_gt_CHP5,…
1) – P_gt_CHP5) * 0.38 <= ones(1, 24) * 65;
problem.Constraints.constraint7 = (circshift(P_gt_CHP5,…
-1) – P_gt_CHP5) * 0.38 <= ones(1, 24) * 85;
problem.Constraints.constraint8 = P_t_cha5 <= u_t_cha5 .* 50;
problem.Constraints.constraint9 = P_t_dis5 <= u_t_dis5 .* 50;
problem.Constraints.constraint10 = u_t_cha5 + u_t_dis5 <= ones(1, 24);
% 设置非默认求解器选项
options5 = optimoptions("ga","Display","iter","PlotFcn",["gaplotscores",…
"gaplotbestf","gaplotbestindiv","gaplotexpectation","gaplotrange"]);
% 求解问题
[solution,objectiveValue] = solve(problem,initialPoint5,"Solver","ga",…
"Options",options5);
% 显示结果
solution
objectiveValue
the output is:
将使用 ga 求解问题。
ERROR – (linprog): Incorrect number of columns in A (inequalities)
ERROR – (linprog): Incorrect number of columns in B (equalities)
警告: (linprog): Length of lower bounds l is too long; ignoring extra bounds
警告: (linprog): Length of upper bounds u is too long; ignoring extra bounds
Output argument "x" (and possibly others) not assigned a value in the execution with "linprog" function.
出错 globaloptim.internal.preProcessLinearConstr (第 166 行)
[XOUT,~,success] = linprog([],Aineq,Bineq,Aeq,Beq,LB,UB, …
出错 gacommon (第 150 行)
globaloptim.internal.preProcessLinearConstr(Iterate.x,Aineq,bineq, …
出错 ga (第 377 行)
NonconFcn,options,Iterate,type] = gacommon(nvars,fun,Aineq,bineq,Aeq,beq,lb,ub, …
出错 optim.problemdef.OptimizationProblem/callSolver
出错 optim.internal.problemdef.ProblemImpl/solveImpl
出错 optim.problemdef.OptimizationProblem/solveP_t_pv = ones(1, 24);
P_tmin_pv = ones(1, 24);
P_t_el = ones(1, 24);
P_t_hl = ones(1, 24);
P_tmin_cl = ones(1, 24);
P_tmax_cl = ones(1, 24);
P_t_net5 = optimvar("P_t_net",1,24,"LowerBound",0);
P_gt_CHP5 = optimvar("P_gt_CHP",1,24,"LowerBound",0);
P_t_cha5 = optimvar("P_t_cha",1,24,"LowerBound",0,"UpperBound",50);
P_t_dis5 = optimvar("P_t_dis",1,24,"LowerBound",0,"UpperBound",50);
u_t_cha5 = optimvar("u_t_cha",1,24,"Type","integer","LowerBound",0,…
"UpperBound",1);
u_t_dis5 = optimvar("u_t_dis",1,24,"Type","integer","LowerBound",0,…
"UpperBound",1);
P_et_EB5 = optimvar("P_et_EB",1,24,"LowerBound",0);
P_et_EC5 = optimvar("P_et_EC",1,24,"LowerBound",0);
P_ht_AC5 = optimvar("P_ht_AC",1,24,"LowerBound",0);
P_gt_GB5 = optimvar("P_gt_GB",1,24,"LowerBound",0);
E_t_f5 = optimvar("E_t_f",1,24,"LowerBound",0);
dP_t_pv5 = optimvar("dP_t_pv",1,24,"LowerBound",0);
dP_t_el5 = optimvar("dP_t_el",1,24,"LowerBound",0);
dP_t_hl5 = optimvar("dP_t_hl",1,24,"LowerBound",0);
dP_t_cl5 = optimvar("dP_t_cl",1,24,"LowerBound",0);
% 设置求解器的初始起点
initialPoint5.P_t_net = zeros(size(P_t_net5));
initialPoint5.P_gt_CHP = zeros(size(P_gt_CHP5));
initialPoint5.P_t_cha = zeros(size(P_t_cha5));
initialPoint5.P_t_dis = zeros(size(P_t_dis5));
initialPoint5.u_t_cha = zeros(size(u_t_cha5));
initialPoint5.u_t_dis = zeros(size(u_t_dis5));
initialPoint5.P_et_EB = zeros(size(P_et_EB5));
initialPoint5.P_et_EC = zeros(size(P_et_EC5));
initialPoint5.P_ht_AC = zeros(size(P_ht_AC5));
initialPoint5.P_gt_GB = zeros(size(P_gt_GB5));
initialPoint5.E_t_f = zeros(size(E_t_f5));
initialPoint5.dP_t_pv = zeros(size(dP_t_pv5));
initialPoint5.dP_t_el = zeros(size(dP_t_el5));
initialPoint5.dP_t_hl = zeros(size(dP_t_hl5));
initialPoint5.dP_t_cl = zeros(size(dP_t_cl5));
% 创建问题
problem = optimproblem;
% 定义问题目标
problem.Objective = fcn2optimexpr(@objectiveFcn,P_t_net5,P_gt_CHP5,P_t_cha5,…
P_et_EB5,P_et_EC5,P_ht_AC5,P_gt_GB5,E_t_f5,dP_t_pv5,dP_t_el5,dP_t_hl5,dP_t_cl5);
% 定义问题约束
problem.Constraints.constraint1 = P_t_net5+0.38*P_gt_CHP5+P_t_pv-dP_t_pv5 == P_t_el-dP_t_el5+P_et_EB5+P_et_EC5+P_t_cha5;
problem.Constraints.constraint2 = P_gt_CHP5*0.45+P_gt_GB5*0.95+P_et_EB5*0.98 == P_t_hl+P_ht_AC5-dP_t_hl5;
problem.Constraints.constraint3 = P_ht_AC5*1.1+P_et_EC5*3.1 >= P_tmin_cl-dP_t_cl5;
problem.Constraints.constraint4 = P_ht_AC5*1.1+P_et_EC5*3.1 <= P_tmax_cl;
problem.Constraints.constraint5 = 0.38*P_gt_CHP5 <= 300 * ones(1, 24);
problem.Constraints.constraint6 = (circshift(P_gt_CHP5,…
1) – P_gt_CHP5) * 0.38 <= ones(1, 24) * 65;
problem.Constraints.constraint7 = (circshift(P_gt_CHP5,…
-1) – P_gt_CHP5) * 0.38 <= ones(1, 24) * 85;
problem.Constraints.constraint8 = P_t_cha5 <= u_t_cha5 .* 50;
problem.Constraints.constraint9 = P_t_dis5 <= u_t_dis5 .* 50;
problem.Constraints.constraint10 = u_t_cha5 + u_t_dis5 <= ones(1, 24);
% 设置非默认求解器选项
options5 = optimoptions("ga","Display","iter","PlotFcn",["gaplotscores",…
"gaplotbestf","gaplotbestindiv","gaplotexpectation","gaplotrange"]);
% 求解问题
[solution,objectiveValue] = solve(problem,initialPoint5,"Solver","ga",…
"Options",options5);
% 显示结果
solution
objectiveValue
the output is:
将使用 ga 求解问题。
ERROR – (linprog): Incorrect number of columns in A (inequalities)
ERROR – (linprog): Incorrect number of columns in B (equalities)
警告: (linprog): Length of lower bounds l is too long; ignoring extra bounds
警告: (linprog): Length of upper bounds u is too long; ignoring extra bounds
Output argument "x" (and possibly others) not assigned a value in the execution with "linprog" function.
出错 globaloptim.internal.preProcessLinearConstr (第 166 行)
[XOUT,~,success] = linprog([],Aineq,Bineq,Aeq,Beq,LB,UB, …
出错 gacommon (第 150 行)
globaloptim.internal.preProcessLinearConstr(Iterate.x,Aineq,bineq, …
出错 ga (第 377 行)
NonconFcn,options,Iterate,type] = gacommon(nvars,fun,Aineq,bineq,Aeq,beq,lb,ub, …
出错 optim.problemdef.OptimizationProblem/callSolver
出错 optim.internal.problemdef.ProblemImpl/solveImpl
出错 optim.problemdef.OptimizationProblem/solve P_t_pv = ones(1, 24);
P_tmin_pv = ones(1, 24);
P_t_el = ones(1, 24);
P_t_hl = ones(1, 24);
P_tmin_cl = ones(1, 24);
P_tmax_cl = ones(1, 24);
P_t_net5 = optimvar("P_t_net",1,24,"LowerBound",0);
P_gt_CHP5 = optimvar("P_gt_CHP",1,24,"LowerBound",0);
P_t_cha5 = optimvar("P_t_cha",1,24,"LowerBound",0,"UpperBound",50);
P_t_dis5 = optimvar("P_t_dis",1,24,"LowerBound",0,"UpperBound",50);
u_t_cha5 = optimvar("u_t_cha",1,24,"Type","integer","LowerBound",0,…
"UpperBound",1);
u_t_dis5 = optimvar("u_t_dis",1,24,"Type","integer","LowerBound",0,…
"UpperBound",1);
P_et_EB5 = optimvar("P_et_EB",1,24,"LowerBound",0);
P_et_EC5 = optimvar("P_et_EC",1,24,"LowerBound",0);
P_ht_AC5 = optimvar("P_ht_AC",1,24,"LowerBound",0);
P_gt_GB5 = optimvar("P_gt_GB",1,24,"LowerBound",0);
E_t_f5 = optimvar("E_t_f",1,24,"LowerBound",0);
dP_t_pv5 = optimvar("dP_t_pv",1,24,"LowerBound",0);
dP_t_el5 = optimvar("dP_t_el",1,24,"LowerBound",0);
dP_t_hl5 = optimvar("dP_t_hl",1,24,"LowerBound",0);
dP_t_cl5 = optimvar("dP_t_cl",1,24,"LowerBound",0);
% 设置求解器的初始起点
initialPoint5.P_t_net = zeros(size(P_t_net5));
initialPoint5.P_gt_CHP = zeros(size(P_gt_CHP5));
initialPoint5.P_t_cha = zeros(size(P_t_cha5));
initialPoint5.P_t_dis = zeros(size(P_t_dis5));
initialPoint5.u_t_cha = zeros(size(u_t_cha5));
initialPoint5.u_t_dis = zeros(size(u_t_dis5));
initialPoint5.P_et_EB = zeros(size(P_et_EB5));
initialPoint5.P_et_EC = zeros(size(P_et_EC5));
initialPoint5.P_ht_AC = zeros(size(P_ht_AC5));
initialPoint5.P_gt_GB = zeros(size(P_gt_GB5));
initialPoint5.E_t_f = zeros(size(E_t_f5));
initialPoint5.dP_t_pv = zeros(size(dP_t_pv5));
initialPoint5.dP_t_el = zeros(size(dP_t_el5));
initialPoint5.dP_t_hl = zeros(size(dP_t_hl5));
initialPoint5.dP_t_cl = zeros(size(dP_t_cl5));
% 创建问题
problem = optimproblem;
% 定义问题目标
problem.Objective = fcn2optimexpr(@objectiveFcn,P_t_net5,P_gt_CHP5,P_t_cha5,…
P_et_EB5,P_et_EC5,P_ht_AC5,P_gt_GB5,E_t_f5,dP_t_pv5,dP_t_el5,dP_t_hl5,dP_t_cl5);
% 定义问题约束
problem.Constraints.constraint1 = P_t_net5+0.38*P_gt_CHP5+P_t_pv-dP_t_pv5 == P_t_el-dP_t_el5+P_et_EB5+P_et_EC5+P_t_cha5;
problem.Constraints.constraint2 = P_gt_CHP5*0.45+P_gt_GB5*0.95+P_et_EB5*0.98 == P_t_hl+P_ht_AC5-dP_t_hl5;
problem.Constraints.constraint3 = P_ht_AC5*1.1+P_et_EC5*3.1 >= P_tmin_cl-dP_t_cl5;
problem.Constraints.constraint4 = P_ht_AC5*1.1+P_et_EC5*3.1 <= P_tmax_cl;
problem.Constraints.constraint5 = 0.38*P_gt_CHP5 <= 300 * ones(1, 24);
problem.Constraints.constraint6 = (circshift(P_gt_CHP5,…
1) – P_gt_CHP5) * 0.38 <= ones(1, 24) * 65;
problem.Constraints.constraint7 = (circshift(P_gt_CHP5,…
-1) – P_gt_CHP5) * 0.38 <= ones(1, 24) * 85;
problem.Constraints.constraint8 = P_t_cha5 <= u_t_cha5 .* 50;
problem.Constraints.constraint9 = P_t_dis5 <= u_t_dis5 .* 50;
problem.Constraints.constraint10 = u_t_cha5 + u_t_dis5 <= ones(1, 24);
% 设置非默认求解器选项
options5 = optimoptions("ga","Display","iter","PlotFcn",["gaplotscores",…
"gaplotbestf","gaplotbestindiv","gaplotexpectation","gaplotrange"]);
% 求解问题
[solution,objectiveValue] = solve(problem,initialPoint5,"Solver","ga",…
"Options",options5);
% 显示结果
solution
objectiveValue
the output is:
将使用 ga 求解问题。
ERROR – (linprog): Incorrect number of columns in A (inequalities)
ERROR – (linprog): Incorrect number of columns in B (equalities)
警告: (linprog): Length of lower bounds l is too long; ignoring extra bounds
警告: (linprog): Length of upper bounds u is too long; ignoring extra bounds
Output argument "x" (and possibly others) not assigned a value in the execution with "linprog" function.
出错 globaloptim.internal.preProcessLinearConstr (第 166 行)
[XOUT,~,success] = linprog([],Aineq,Bineq,Aeq,Beq,LB,UB, …
出错 gacommon (第 150 行)
globaloptim.internal.preProcessLinearConstr(Iterate.x,Aineq,bineq, …
出错 ga (第 377 行)
NonconFcn,options,Iterate,type] = gacommon(nvars,fun,Aineq,bineq,Aeq,beq,lb,ub, …
出错 optim.problemdef.OptimizationProblem/callSolver
出错 optim.internal.problemdef.ProblemImpl/solveImpl
出错 optim.problemdef.OptimizationProblem/solve ga, optimization MATLAB Answers — New Questions
Old Matlab example of 1D FFT filter
I remember that in one of the old Matlab version (2010 or even earlier), in its Help was shown example of the application FFT – IFFT filter to remove noise frequency components of signal, which was close to the sinusoidal. Example was short and useful, but now I need something similar, and can’t find it. Is it possible to recover it?I remember that in one of the old Matlab version (2010 or even earlier), in its Help was shown example of the application FFT – IFFT filter to remove noise frequency components of signal, which was close to the sinusoidal. Example was short and useful, but now I need something similar, and can’t find it. Is it possible to recover it? I remember that in one of the old Matlab version (2010 or even earlier), in its Help was shown example of the application FFT – IFFT filter to remove noise frequency components of signal, which was close to the sinusoidal. Example was short and useful, but now I need something similar, and can’t find it. Is it possible to recover it? fft, fft-ifft filter MATLAB Answers — New Questions
Can’t get matrix to populate first column
So I’m trying to create a matrix that changes between 3 possible values based on modified values of a different matrix, here’s the code:
z=linspace(1,cap,cap)’;
y=linspace(1,cap,cap)’;
f=@(x,y) x-y;
M=f(z.’,y);
p=zeros(size(M));
z1=z+1; %dem went to patch 1 and found food
z1(z1>cap)=cap;
for j=1:15
for k=1:15
if M(j,z1(k))>0
p(j,z1(k))=0.9;
elseif M(j,z1(k))<0
p(j,z1(k))=0.1;
else
p(j,z1(k))=0.5;
end
How do I get that first column to populate correctly?
I have multiple of these p matrices with different modifiers and some of them populate the entire matrix while others are missing a column or rowSo I’m trying to create a matrix that changes between 3 possible values based on modified values of a different matrix, here’s the code:
z=linspace(1,cap,cap)’;
y=linspace(1,cap,cap)’;
f=@(x,y) x-y;
M=f(z.’,y);
p=zeros(size(M));
z1=z+1; %dem went to patch 1 and found food
z1(z1>cap)=cap;
for j=1:15
for k=1:15
if M(j,z1(k))>0
p(j,z1(k))=0.9;
elseif M(j,z1(k))<0
p(j,z1(k))=0.1;
else
p(j,z1(k))=0.5;
end
How do I get that first column to populate correctly?
I have multiple of these p matrices with different modifiers and some of them populate the entire matrix while others are missing a column or row So I’m trying to create a matrix that changes between 3 possible values based on modified values of a different matrix, here’s the code:
z=linspace(1,cap,cap)’;
y=linspace(1,cap,cap)’;
f=@(x,y) x-y;
M=f(z.’,y);
p=zeros(size(M));
z1=z+1; %dem went to patch 1 and found food
z1(z1>cap)=cap;
for j=1:15
for k=1:15
if M(j,z1(k))>0
p(j,z1(k))=0.9;
elseif M(j,z1(k))<0
p(j,z1(k))=0.1;
else
p(j,z1(k))=0.5;
end
How do I get that first column to populate correctly?
I have multiple of these p matrices with different modifiers and some of them populate the entire matrix while others are missing a column or row matrix, matrix array MATLAB Answers — New Questions
Output problem for If – statement in For – Loop
This is a part of my code:
answerCoordinates = [238, 285; 152, 130; 108, 565; 489, 557; 238, 287; 289, 557; 530, 335];
for i = 1:size(answerCoordinates, 1)
answerX = answerCoordinates(i, 1);
answerY = answerCoordinates(i, 2);
if x >= (answerX – 25) && x <= (answerX + 25) && y >= (answerY – 25) && y <= (answerY + 25)
fprintf("You have found a new spot! n");
fprintf("Current Progress: %d/5 n",currentLoop)
currentLoop = currentLoop + 1
% else
% stopThegame = stopThegame + 1
% else
% fprintf("Ops!Wrong Spot!Start Again!")
% rect = findall(gcf,’Type’, ‘Rectangle’);
% delete(rect);
% currentLoop = 1
end
% if stopThegame ~= 7
% fprintf("Ops!Wrong Spot!Start Again!")
% rect = findall(gcf,’Type’, ‘Rectangle’);
% delete(rect);
% currentLoop = 1
% end
end
The for loop will iterate 7 times, considering there are only 7 answers. The if-statement aims to identify whether the user’s entered coordinate matches one of the answer coordinates. I’m having difficulty outputting the value when the user’s coordinate doesn’t match any of the answer coordinates. The section involving ‘%’ is my attempt to address this issue, but it hasn’t been successful so far.
How can I solve this problem?This is a part of my code:
answerCoordinates = [238, 285; 152, 130; 108, 565; 489, 557; 238, 287; 289, 557; 530, 335];
for i = 1:size(answerCoordinates, 1)
answerX = answerCoordinates(i, 1);
answerY = answerCoordinates(i, 2);
if x >= (answerX – 25) && x <= (answerX + 25) && y >= (answerY – 25) && y <= (answerY + 25)
fprintf("You have found a new spot! n");
fprintf("Current Progress: %d/5 n",currentLoop)
currentLoop = currentLoop + 1
% else
% stopThegame = stopThegame + 1
% else
% fprintf("Ops!Wrong Spot!Start Again!")
% rect = findall(gcf,’Type’, ‘Rectangle’);
% delete(rect);
% currentLoop = 1
end
% if stopThegame ~= 7
% fprintf("Ops!Wrong Spot!Start Again!")
% rect = findall(gcf,’Type’, ‘Rectangle’);
% delete(rect);
% currentLoop = 1
% end
end
The for loop will iterate 7 times, considering there are only 7 answers. The if-statement aims to identify whether the user’s entered coordinate matches one of the answer coordinates. I’m having difficulty outputting the value when the user’s coordinate doesn’t match any of the answer coordinates. The section involving ‘%’ is my attempt to address this issue, but it hasn’t been successful so far.
How can I solve this problem? This is a part of my code:
answerCoordinates = [238, 285; 152, 130; 108, 565; 489, 557; 238, 287; 289, 557; 530, 335];
for i = 1:size(answerCoordinates, 1)
answerX = answerCoordinates(i, 1);
answerY = answerCoordinates(i, 2);
if x >= (answerX – 25) && x <= (answerX + 25) && y >= (answerY – 25) && y <= (answerY + 25)
fprintf("You have found a new spot! n");
fprintf("Current Progress: %d/5 n",currentLoop)
currentLoop = currentLoop + 1
% else
% stopThegame = stopThegame + 1
% else
% fprintf("Ops!Wrong Spot!Start Again!")
% rect = findall(gcf,’Type’, ‘Rectangle’);
% delete(rect);
% currentLoop = 1
end
% if stopThegame ~= 7
% fprintf("Ops!Wrong Spot!Start Again!")
% rect = findall(gcf,’Type’, ‘Rectangle’);
% delete(rect);
% currentLoop = 1
% end
end
The for loop will iterate 7 times, considering there are only 7 answers. The if-statement aims to identify whether the user’s entered coordinate matches one of the answer coordinates. I’m having difficulty outputting the value when the user’s coordinate doesn’t match any of the answer coordinates. The section involving ‘%’ is my attempt to address this issue, but it hasn’t been successful so far.
How can I solve this problem? for loop, if statement, output MATLAB Answers — New Questions
automatic change in variable’s value during optimisation
I am currently working on optimising the cost of charge of an electric vehicule by scheduling a charging/discharging process during 9 intervals.
During the process an uncertainty of battery degradation occures in a specific interval, the capacity is reduced from 60ah to 58.2ah.
My question is to how to update the new value while the code is running so the optimisation algorithm performs a rescheduing based on the new value ? Thank you.I am currently working on optimising the cost of charge of an electric vehicule by scheduling a charging/discharging process during 9 intervals.
During the process an uncertainty of battery degradation occures in a specific interval, the capacity is reduced from 60ah to 58.2ah.
My question is to how to update the new value while the code is running so the optimisation algorithm performs a rescheduing based on the new value ? Thank you. I am currently working on optimising the cost of charge of an electric vehicule by scheduling a charging/discharging process during 9 intervals.
During the process an uncertainty of battery degradation occures in a specific interval, the capacity is reduced from 60ah to 58.2ah.
My question is to how to update the new value while the code is running so the optimisation algorithm performs a rescheduing based on the new value ? Thank you. variable, optimization, matlab, scheduling MATLAB Answers — New Questions
backtestEngine / runBacktest speed of execution / parallelisation
Hi Experts,
Do we know whether runBacktest (part of backtestEngine) does any parallel execution … on timatables having daily data (say, up to 10K lines), daily rebalance is "bareable" – however, the higher the table, the slower the execution. Looking at the CPU, it doesn’t look like parfor is being used at all. Basically, getting on higher time resolution, anything other than daily bars (such as hourly, minute, etc.) – it gets practically impossible to execute a runBacktest on a bar by bar rebalance, even on a very small number of tickers / instruments / timetable columns (take 20 for example, forget about taking a full index).
ThanksHi Experts,
Do we know whether runBacktest (part of backtestEngine) does any parallel execution … on timatables having daily data (say, up to 10K lines), daily rebalance is "bareable" – however, the higher the table, the slower the execution. Looking at the CPU, it doesn’t look like parfor is being used at all. Basically, getting on higher time resolution, anything other than daily bars (such as hourly, minute, etc.) – it gets practically impossible to execute a runBacktest on a bar by bar rebalance, even on a very small number of tickers / instruments / timetable columns (take 20 for example, forget about taking a full index).
Thanks Hi Experts,
Do we know whether runBacktest (part of backtestEngine) does any parallel execution … on timatables having daily data (say, up to 10K lines), daily rebalance is "bareable" – however, the higher the table, the slower the execution. Looking at the CPU, it doesn’t look like parfor is being used at all. Basically, getting on higher time resolution, anything other than daily bars (such as hourly, minute, etc.) – it gets practically impossible to execute a runBacktest on a bar by bar rebalance, even on a very small number of tickers / instruments / timetable columns (take 20 for example, forget about taking a full index).
Thanks backtestengine, runbacktest, backteststrategy, rebalancefrequency, financial toolbox, quantitative finance MATLAB Answers — New Questions
How to use boxchart and GroupByColor when having a matrix?
Dear all,
I am trying to use a boxchart for plotting a (10000,10) matrix, where each column represents a single box.
In other words, I would like to plot a boxchart consisting of 10 boxes and 10,000 data points.
The problem is that all Answers in the forum I have read so far are related to vectors, not matrices. All my attempts of using boxchart have resulted in an error, which states that I cannot use a matrix but vectors. Transforming the matrix into a vector is not possible. Additionally, I would like to group the 10 columns in 3 categories by assigning each box the respective color:
column [1 2 3 4 5 6 7 8 9 10]
group [A A B C C B A B C A]
color: [r r g b b g r g b r ]
However, I cannot provide a vector with values and tell Matlab to group the columns of the matrix on the basis of a specific threshold (e.g. temperature), but I have to do this manually by paper and pencil and inform Matlab which column belongs to which group myself.
I use the following code:
figure (2)
groupname={‘A’,’A’,’B’,’C’,’C’,’B’,’A’,’B’,’C’,’A’}’;
boxchart(AX.t_k,’MarkerStyle’, ‘none’,’GroupByColor’, groupname); % AX.t_k = (10000,10) matrix
And I get the following error:
Error using boxchart
‘GroupByColor’ parameter is not supported when the sample data argument is a matrix.
Could someone tell me, how I can use boxchart when using a matrix and how I can group each column with their respective color?
Thank you very much for your help!Dear all,
I am trying to use a boxchart for plotting a (10000,10) matrix, where each column represents a single box.
In other words, I would like to plot a boxchart consisting of 10 boxes and 10,000 data points.
The problem is that all Answers in the forum I have read so far are related to vectors, not matrices. All my attempts of using boxchart have resulted in an error, which states that I cannot use a matrix but vectors. Transforming the matrix into a vector is not possible. Additionally, I would like to group the 10 columns in 3 categories by assigning each box the respective color:
column [1 2 3 4 5 6 7 8 9 10]
group [A A B C C B A B C A]
color: [r r g b b g r g b r ]
However, I cannot provide a vector with values and tell Matlab to group the columns of the matrix on the basis of a specific threshold (e.g. temperature), but I have to do this manually by paper and pencil and inform Matlab which column belongs to which group myself.
I use the following code:
figure (2)
groupname={‘A’,’A’,’B’,’C’,’C’,’B’,’A’,’B’,’C’,’A’}’;
boxchart(AX.t_k,’MarkerStyle’, ‘none’,’GroupByColor’, groupname); % AX.t_k = (10000,10) matrix
And I get the following error:
Error using boxchart
‘GroupByColor’ parameter is not supported when the sample data argument is a matrix.
Could someone tell me, how I can use boxchart when using a matrix and how I can group each column with their respective color?
Thank you very much for your help! Dear all,
I am trying to use a boxchart for plotting a (10000,10) matrix, where each column represents a single box.
In other words, I would like to plot a boxchart consisting of 10 boxes and 10,000 data points.
The problem is that all Answers in the forum I have read so far are related to vectors, not matrices. All my attempts of using boxchart have resulted in an error, which states that I cannot use a matrix but vectors. Transforming the matrix into a vector is not possible. Additionally, I would like to group the 10 columns in 3 categories by assigning each box the respective color:
column [1 2 3 4 5 6 7 8 9 10]
group [A A B C C B A B C A]
color: [r r g b b g r g b r ]
However, I cannot provide a vector with values and tell Matlab to group the columns of the matrix on the basis of a specific threshold (e.g. temperature), but I have to do this manually by paper and pencil and inform Matlab which column belongs to which group myself.
I use the following code:
figure (2)
groupname={‘A’,’A’,’B’,’C’,’C’,’B’,’A’,’B’,’C’,’A’}’;
boxchart(AX.t_k,’MarkerStyle’, ‘none’,’GroupByColor’, groupname); % AX.t_k = (10000,10) matrix
And I get the following error:
Error using boxchart
‘GroupByColor’ parameter is not supported when the sample data argument is a matrix.
Could someone tell me, how I can use boxchart when using a matrix and how I can group each column with their respective color?
Thank you very much for your help! boxchart, matrix, color MATLAB Answers — New Questions
Setting up an optimization in matlab
Hi everyone.
I have an optimization problem that seeks to aid the selection of suitable conductors in a network planning exercise. I have set up two functions – one of the functions sets up the objective function which is to calculate the total cost based on the type of conductor and the cost associated with the type of conductor. The total cost is thus calculated based on the code below.
function TotCost = minTotCost(RepCondpath,fdrpath1,sheetname)
%fdrpath1: describes the path to the an excel file with the conductors on
%the network while RepCondpath described the path to the costs associated
%with each type of conductor.
[TR,TAmp, C_index]=rep_repository_cr_opt(RepCondpath);
[R,Amp]=getInitialCon_par(fdrpath1,sheetname);
% examine the Resistance of the conductor
% check the TR to find out the value of the
C_weights=C_index;
cost =zeros(length(R),1);
for i =1:length (R)
disp(i);
j= TR == R(i);
cost(i) = C_weights(j);
end
TotCost= sum(cost);
The second thing is to describe the constraints function. In this case, the two constraints are voltage levels (NPI) and conductor loading (CPI). These two are calculated based on the a powerflow function- which calculate the network’s NPI and CPI using the following constraint function.
function[NPI,CPI]=ConstraintFnc(fdrpath1,sheetname)
fname1 = fdrpath1;sheet = sheetname;
fdrcon=get_fdrcon(fdrpath1,sheetname);
[VA,VB,VC,~,IA,IB,IC]= start_f7(1,1,1,1,sheetname,fdrpath1); % This is the powerflow function
ResRange1 = "G6:G12"; AmpRange="AG6:AG12";
R=xlsread(fname1,sheet,ResRange1);
Amp=xlsread(fname1,sheet,AmpRange);
[CPI,NPI]= BNPerf_opt(VA, VB, VC, IA, IB, IC); % This is the function that calculates the CPI and NPI
The objective is to find conductors in TR whose combination has the least total cost. How do I bring these two functions together to run on Matlab.Hi everyone.
I have an optimization problem that seeks to aid the selection of suitable conductors in a network planning exercise. I have set up two functions – one of the functions sets up the objective function which is to calculate the total cost based on the type of conductor and the cost associated with the type of conductor. The total cost is thus calculated based on the code below.
function TotCost = minTotCost(RepCondpath,fdrpath1,sheetname)
%fdrpath1: describes the path to the an excel file with the conductors on
%the network while RepCondpath described the path to the costs associated
%with each type of conductor.
[TR,TAmp, C_index]=rep_repository_cr_opt(RepCondpath);
[R,Amp]=getInitialCon_par(fdrpath1,sheetname);
% examine the Resistance of the conductor
% check the TR to find out the value of the
C_weights=C_index;
cost =zeros(length(R),1);
for i =1:length (R)
disp(i);
j= TR == R(i);
cost(i) = C_weights(j);
end
TotCost= sum(cost);
The second thing is to describe the constraints function. In this case, the two constraints are voltage levels (NPI) and conductor loading (CPI). These two are calculated based on the a powerflow function- which calculate the network’s NPI and CPI using the following constraint function.
function[NPI,CPI]=ConstraintFnc(fdrpath1,sheetname)
fname1 = fdrpath1;sheet = sheetname;
fdrcon=get_fdrcon(fdrpath1,sheetname);
[VA,VB,VC,~,IA,IB,IC]= start_f7(1,1,1,1,sheetname,fdrpath1); % This is the powerflow function
ResRange1 = "G6:G12"; AmpRange="AG6:AG12";
R=xlsread(fname1,sheet,ResRange1);
Amp=xlsread(fname1,sheet,AmpRange);
[CPI,NPI]= BNPerf_opt(VA, VB, VC, IA, IB, IC); % This is the function that calculates the CPI and NPI
The objective is to find conductors in TR whose combination has the least total cost. How do I bring these two functions together to run on Matlab. Hi everyone.
I have an optimization problem that seeks to aid the selection of suitable conductors in a network planning exercise. I have set up two functions – one of the functions sets up the objective function which is to calculate the total cost based on the type of conductor and the cost associated with the type of conductor. The total cost is thus calculated based on the code below.
function TotCost = minTotCost(RepCondpath,fdrpath1,sheetname)
%fdrpath1: describes the path to the an excel file with the conductors on
%the network while RepCondpath described the path to the costs associated
%with each type of conductor.
[TR,TAmp, C_index]=rep_repository_cr_opt(RepCondpath);
[R,Amp]=getInitialCon_par(fdrpath1,sheetname);
% examine the Resistance of the conductor
% check the TR to find out the value of the
C_weights=C_index;
cost =zeros(length(R),1);
for i =1:length (R)
disp(i);
j= TR == R(i);
cost(i) = C_weights(j);
end
TotCost= sum(cost);
The second thing is to describe the constraints function. In this case, the two constraints are voltage levels (NPI) and conductor loading (CPI). These two are calculated based on the a powerflow function- which calculate the network’s NPI and CPI using the following constraint function.
function[NPI,CPI]=ConstraintFnc(fdrpath1,sheetname)
fname1 = fdrpath1;sheet = sheetname;
fdrcon=get_fdrcon(fdrpath1,sheetname);
[VA,VB,VC,~,IA,IB,IC]= start_f7(1,1,1,1,sheetname,fdrpath1); % This is the powerflow function
ResRange1 = "G6:G12"; AmpRange="AG6:AG12";
R=xlsread(fname1,sheet,ResRange1);
Amp=xlsread(fname1,sheet,AmpRange);
[CPI,NPI]= BNPerf_opt(VA, VB, VC, IA, IB, IC); % This is the function that calculates the CPI and NPI
The objective is to find conductors in TR whose combination has the least total cost. How do I bring these two functions together to run on Matlab. ga, optimization, conductor selection MATLAB Answers — New Questions
How do I feed ODE45 a cell array ?
I am trying to solve an ODE which consists of function handles. In order to formulate the equation of state vector derivative of the System of 1st order ODEs, I collect these function handles in a cell array. It is not possible to store them in a normal array as far as I know. How do I feed the cell Array, which contains all the function handles to the ODE45 solver or do it differently?
Scheme of the problem:
%create cell and state array
state = @(x,y,z) [x;y;z];
Cell_array = cell(3);
%column selector
select_column = @(M, col_index) M(:,col_index);
%Define Matrix Functions, here 2 examples of Matrices
Matrix_1 = @(state) [1,1,state(1); 1,1,sin(state(2));1,1,state(3)];
Matrix_2 = @(state) [state(1),0,0; 0,state(2),0; 0,0, state(2)];
%select the columns
M1_c1 = @(state) select_column(Matrix_1(state),1);
M1_c2 = @(state) select_column(Matrix_1(state),2);
M1_c3 = @(state) select_column(Matrix_1(state),3);
%differential equations
state_dot_1 = @(state) Matrix_2(state) * M1_c1(state);
state_dot_2 = @(state) Matrix_2(state) * M1_c2(state);
state_dot_3 = @(state) Matrix_2(state) * M1_c3(state);
%fill cell array with differential equations
Cell_array{1} = state_dot_1;
Cell_array{2} = state_dot_2;
Cell_array{3} = state_dot_3;
I would now like to feed that cell_array to an ODE solver. This doesn’t work. But using a normal array doesn’t work either for these function handles. Does anyone know a work around ? I’m new to matlab and programming in general.I am trying to solve an ODE which consists of function handles. In order to formulate the equation of state vector derivative of the System of 1st order ODEs, I collect these function handles in a cell array. It is not possible to store them in a normal array as far as I know. How do I feed the cell Array, which contains all the function handles to the ODE45 solver or do it differently?
Scheme of the problem:
%create cell and state array
state = @(x,y,z) [x;y;z];
Cell_array = cell(3);
%column selector
select_column = @(M, col_index) M(:,col_index);
%Define Matrix Functions, here 2 examples of Matrices
Matrix_1 = @(state) [1,1,state(1); 1,1,sin(state(2));1,1,state(3)];
Matrix_2 = @(state) [state(1),0,0; 0,state(2),0; 0,0, state(2)];
%select the columns
M1_c1 = @(state) select_column(Matrix_1(state),1);
M1_c2 = @(state) select_column(Matrix_1(state),2);
M1_c3 = @(state) select_column(Matrix_1(state),3);
%differential equations
state_dot_1 = @(state) Matrix_2(state) * M1_c1(state);
state_dot_2 = @(state) Matrix_2(state) * M1_c2(state);
state_dot_3 = @(state) Matrix_2(state) * M1_c3(state);
%fill cell array with differential equations
Cell_array{1} = state_dot_1;
Cell_array{2} = state_dot_2;
Cell_array{3} = state_dot_3;
I would now like to feed that cell_array to an ODE solver. This doesn’t work. But using a normal array doesn’t work either for these function handles. Does anyone know a work around ? I’m new to matlab and programming in general. I am trying to solve an ODE which consists of function handles. In order to formulate the equation of state vector derivative of the System of 1st order ODEs, I collect these function handles in a cell array. It is not possible to store them in a normal array as far as I know. How do I feed the cell Array, which contains all the function handles to the ODE45 solver or do it differently?
Scheme of the problem:
%create cell and state array
state = @(x,y,z) [x;y;z];
Cell_array = cell(3);
%column selector
select_column = @(M, col_index) M(:,col_index);
%Define Matrix Functions, here 2 examples of Matrices
Matrix_1 = @(state) [1,1,state(1); 1,1,sin(state(2));1,1,state(3)];
Matrix_2 = @(state) [state(1),0,0; 0,state(2),0; 0,0, state(2)];
%select the columns
M1_c1 = @(state) select_column(Matrix_1(state),1);
M1_c2 = @(state) select_column(Matrix_1(state),2);
M1_c3 = @(state) select_column(Matrix_1(state),3);
%differential equations
state_dot_1 = @(state) Matrix_2(state) * M1_c1(state);
state_dot_2 = @(state) Matrix_2(state) * M1_c2(state);
state_dot_3 = @(state) Matrix_2(state) * M1_c3(state);
%fill cell array with differential equations
Cell_array{1} = state_dot_1;
Cell_array{2} = state_dot_2;
Cell_array{3} = state_dot_3;
I would now like to feed that cell_array to an ODE solver. This doesn’t work. But using a normal array doesn’t work either for these function handles. Does anyone know a work around ? I’m new to matlab and programming in general. function handles, ode45, cell array MATLAB Answers — New Questions
How to resolve this error: Unable to perform assignment because the size of the left side is 1000-by-1 and the size of the right side is 1000-by-1000
Howe to resolve this error:
Unable to perform assignment because the size of the left side is 1000-by-1 and the size of the right
side is 1000-by-1000.
Error in servssnr (line 43)
ynoisy(:,ii) = awgn(real(y),snr(ii),’measured’); % Add AWGN
This is my full code:
PRF = 500e3; % Pulse Repetition Frequency (Hz)
sampling_freq = 60e6; % Sampling Frequency (Hz)
carrier_freq = 2.4e9;
rng(‘default’) % Set random number seed for repeatability
M = 4;
EbNo = 0:13;
[ber,ser] = berawgn(EbNo,’pam’,M);
n = 1000; % Number of symbols to process
k = log2(M); % Number of bits per symbol
snr = EbNo+3+10*log10(k); % In dB
ynoisy = zeros(n,length(snr));
z = zeros(n,length(snr));
errVec = zeros(3,length(EbNo));
grid on;
errcalc = comm.ErrorRate;
%x1 = randi([0 M-1],n,1); % Create message signal
% Generate Gold code
code1 = comm.GoldSequence(‘FirstPolynomial’,’x^6+x^5+1′, ‘FirstInitialConditions’,[ 0 0 0 0 0 1], ‘SecondPolynomial’,’x^6+x^5+x^4+x+1′, ‘SecondInitialConditions’,[0 0 0 0 0 1], ‘Index’,1, ‘SamplesPerFrame’,1000);
gold_code = code1();
% Generate Kasami code
kasamiseq = comm.KasamiSequence(‘Polynomial’,[6 5 4 1 0], ‘InitialConditions’,[ 0 0 0 0 0 1],’SamplesPerFrame’,1000);
kasami_code = kasamiseq()
y1 = pammod(gold_code,M); % Modulate
for ii = 1:length(snr)
reset(errcalc)
ynoisy(:,ii) = awgn(real(y1),snr(ii),’measured’); % Add AWGN
z(:,ii) = pamdemod(complex(ynoisy(:,ii)),M); % Demodulate
errVec(:,ii) = errcalc(gold_code,z(:,ii)); % Compute SER from simulation
end
semilogy(EbNo,errVec(1,:),’r’);
hold on;
% Modulate kasami code with barker code
x5 = cos(2*pi*carrier_freq*(0:numel(gold_code)-1)/sampling_freq) .* (gold_code .* kasami_code.’);
y = pammod(x5,M); % Modulate
for ii = 1:length(snr)
reset(errcalc)
ynoisy(:,ii) = awgn(real(y),snr(ii),’measured’); % Add AWGN
z(:,ii) = pamdemod(complex(ynoisy(:,ii)),M); % Demodulate
errVec(:,ii) = errcalc(x5,z(:,ii)); % Compute SER from simulation
end
semilogy(EbNo,errVec(1,:),’b’);
hold on;
y2 = pammod(kasami_code,M);
for ii = 1:length(snr)
reset(errcalc)
ynoisy(:,ii) = awgn(real(y2),snr(ii),’measured’); % Add AWGN
z(:,ii) = pamdemod(complex(ynoisy(:,ii)),M); % Demodulate
errVec(:,ii) = errcalc(kasami_code,z(:,ii)); % Compute SER from simulation
end
semilogy(EbNo,errVec(1,:),’g’);
legend(‘Gold code’,’Gold-Kasami’, ‘Kasami’);
title(‘Comparison of SER ‘);
xlabel(‘E_b/N_0 (dB)’);
ylabel(‘Symbol Error Rate’);
grid on;
hold off;Howe to resolve this error:
Unable to perform assignment because the size of the left side is 1000-by-1 and the size of the right
side is 1000-by-1000.
Error in servssnr (line 43)
ynoisy(:,ii) = awgn(real(y),snr(ii),’measured’); % Add AWGN
This is my full code:
PRF = 500e3; % Pulse Repetition Frequency (Hz)
sampling_freq = 60e6; % Sampling Frequency (Hz)
carrier_freq = 2.4e9;
rng(‘default’) % Set random number seed for repeatability
M = 4;
EbNo = 0:13;
[ber,ser] = berawgn(EbNo,’pam’,M);
n = 1000; % Number of symbols to process
k = log2(M); % Number of bits per symbol
snr = EbNo+3+10*log10(k); % In dB
ynoisy = zeros(n,length(snr));
z = zeros(n,length(snr));
errVec = zeros(3,length(EbNo));
grid on;
errcalc = comm.ErrorRate;
%x1 = randi([0 M-1],n,1); % Create message signal
% Generate Gold code
code1 = comm.GoldSequence(‘FirstPolynomial’,’x^6+x^5+1′, ‘FirstInitialConditions’,[ 0 0 0 0 0 1], ‘SecondPolynomial’,’x^6+x^5+x^4+x+1′, ‘SecondInitialConditions’,[0 0 0 0 0 1], ‘Index’,1, ‘SamplesPerFrame’,1000);
gold_code = code1();
% Generate Kasami code
kasamiseq = comm.KasamiSequence(‘Polynomial’,[6 5 4 1 0], ‘InitialConditions’,[ 0 0 0 0 0 1],’SamplesPerFrame’,1000);
kasami_code = kasamiseq()
y1 = pammod(gold_code,M); % Modulate
for ii = 1:length(snr)
reset(errcalc)
ynoisy(:,ii) = awgn(real(y1),snr(ii),’measured’); % Add AWGN
z(:,ii) = pamdemod(complex(ynoisy(:,ii)),M); % Demodulate
errVec(:,ii) = errcalc(gold_code,z(:,ii)); % Compute SER from simulation
end
semilogy(EbNo,errVec(1,:),’r’);
hold on;
% Modulate kasami code with barker code
x5 = cos(2*pi*carrier_freq*(0:numel(gold_code)-1)/sampling_freq) .* (gold_code .* kasami_code.’);
y = pammod(x5,M); % Modulate
for ii = 1:length(snr)
reset(errcalc)
ynoisy(:,ii) = awgn(real(y),snr(ii),’measured’); % Add AWGN
z(:,ii) = pamdemod(complex(ynoisy(:,ii)),M); % Demodulate
errVec(:,ii) = errcalc(x5,z(:,ii)); % Compute SER from simulation
end
semilogy(EbNo,errVec(1,:),’b’);
hold on;
y2 = pammod(kasami_code,M);
for ii = 1:length(snr)
reset(errcalc)
ynoisy(:,ii) = awgn(real(y2),snr(ii),’measured’); % Add AWGN
z(:,ii) = pamdemod(complex(ynoisy(:,ii)),M); % Demodulate
errVec(:,ii) = errcalc(kasami_code,z(:,ii)); % Compute SER from simulation
end
semilogy(EbNo,errVec(1,:),’g’);
legend(‘Gold code’,’Gold-Kasami’, ‘Kasami’);
title(‘Comparison of SER ‘);
xlabel(‘E_b/N_0 (dB)’);
ylabel(‘Symbol Error Rate’);
grid on;
hold off; Howe to resolve this error:
Unable to perform assignment because the size of the left side is 1000-by-1 and the size of the right
side is 1000-by-1000.
Error in servssnr (line 43)
ynoisy(:,ii) = awgn(real(y),snr(ii),’measured’); % Add AWGN
This is my full code:
PRF = 500e3; % Pulse Repetition Frequency (Hz)
sampling_freq = 60e6; % Sampling Frequency (Hz)
carrier_freq = 2.4e9;
rng(‘default’) % Set random number seed for repeatability
M = 4;
EbNo = 0:13;
[ber,ser] = berawgn(EbNo,’pam’,M);
n = 1000; % Number of symbols to process
k = log2(M); % Number of bits per symbol
snr = EbNo+3+10*log10(k); % In dB
ynoisy = zeros(n,length(snr));
z = zeros(n,length(snr));
errVec = zeros(3,length(EbNo));
grid on;
errcalc = comm.ErrorRate;
%x1 = randi([0 M-1],n,1); % Create message signal
% Generate Gold code
code1 = comm.GoldSequence(‘FirstPolynomial’,’x^6+x^5+1′, ‘FirstInitialConditions’,[ 0 0 0 0 0 1], ‘SecondPolynomial’,’x^6+x^5+x^4+x+1′, ‘SecondInitialConditions’,[0 0 0 0 0 1], ‘Index’,1, ‘SamplesPerFrame’,1000);
gold_code = code1();
% Generate Kasami code
kasamiseq = comm.KasamiSequence(‘Polynomial’,[6 5 4 1 0], ‘InitialConditions’,[ 0 0 0 0 0 1],’SamplesPerFrame’,1000);
kasami_code = kasamiseq()
y1 = pammod(gold_code,M); % Modulate
for ii = 1:length(snr)
reset(errcalc)
ynoisy(:,ii) = awgn(real(y1),snr(ii),’measured’); % Add AWGN
z(:,ii) = pamdemod(complex(ynoisy(:,ii)),M); % Demodulate
errVec(:,ii) = errcalc(gold_code,z(:,ii)); % Compute SER from simulation
end
semilogy(EbNo,errVec(1,:),’r’);
hold on;
% Modulate kasami code with barker code
x5 = cos(2*pi*carrier_freq*(0:numel(gold_code)-1)/sampling_freq) .* (gold_code .* kasami_code.’);
y = pammod(x5,M); % Modulate
for ii = 1:length(snr)
reset(errcalc)
ynoisy(:,ii) = awgn(real(y),snr(ii),’measured’); % Add AWGN
z(:,ii) = pamdemod(complex(ynoisy(:,ii)),M); % Demodulate
errVec(:,ii) = errcalc(x5,z(:,ii)); % Compute SER from simulation
end
semilogy(EbNo,errVec(1,:),’b’);
hold on;
y2 = pammod(kasami_code,M);
for ii = 1:length(snr)
reset(errcalc)
ynoisy(:,ii) = awgn(real(y2),snr(ii),’measured’); % Add AWGN
z(:,ii) = pamdemod(complex(ynoisy(:,ii)),M); % Demodulate
errVec(:,ii) = errcalc(kasami_code,z(:,ii)); % Compute SER from simulation
end
semilogy(EbNo,errVec(1,:),’g’);
legend(‘Gold code’,’Gold-Kasami’, ‘Kasami’);
title(‘Comparison of SER ‘);
xlabel(‘E_b/N_0 (dB)’);
ylabel(‘Symbol Error Rate’);
grid on;
hold off; matlab, digital signal processing, radar, error, dimensions, binary MATLAB Answers — New Questions
How would I properly go about creating this function?
I am doing a project to practice matlab and thought it would be best to be put into a function. This is my function and the rest of my code, I have variables t_values, height_values, and width_values that need to be used outside of the function, but I do not know how to use them from inside the function. These equations are going to be different for the different beams which is why I decided to create a general function. Thanks!
l = 70*12; %length
maxHeight = 12; %maximum height of beam
maxWidth = 10; %maximum width of beam
minHeight = 3; %minimum height of beam
minWidth = 3; %minimum width of beam
maxDef = 10; %maximum beam deformation
w = 3; %distributed load
p = 500; %point force
a = l/3; %distance to point force
E_alum = 9.9*10^6; %aluminum stiffness
E_steel = 28*10^6; %steel stiffness
E_ti = 16*10^6; %titanium stiffness
den_alum = .098; %aluminum density
den_steel = .286; %steel density
den_ti = .16; %titanium density
E = [E_alum, E_steel, E_ti];
density = [den_alum, den_steel, den_ti];
%For combined load
I_min = (w*(l^4)./(E.*30.*maxDef))…
– ((p*(a^2)*((3*l)-a))./(E.*6.*maxDef));
disp(‘I-Beam’);
A_horizI = width_values.*t_values; %Area of flanges
A_vertI = t_values.*(height_values-(2.*t_values)); %Area of web
I_horizI = width_values.*t_values.^3; %Moment of flanges
I_vertI = (t_values.*(height_values-(2.*t_values)).^3)./12; %Moment of web
I_I_beam = I_vertI + 2.*(I_horizI + A_horizI.*((height_values./2)-(t_values./2)).^2); %I for I beam
weightIbeam = @(t, h, w, l, density) (2*w.*t + t.*(h-2.*t))*l*density; %Weight equation for I beam
beamoptimize(I_min, l, density,I_I_beam,weightIbeam);
function beamoptimize( I_min, l, density, I1, weightFunc)
t = 0.1:0.05:1;
height = minHeight:0.05:maxHeight;
width = minWidth:0.05:maxWidth;
V = {t, height, width};
C = cell(1, numel(V));
[C{:}] = ndgrid(V{:});
C = cellfun(@(X) reshape(X, [], 1), C, ‘UniformOutput’, false);
C = horzcat(C{:});
t_values = C(:, 1);
height_values = C(:, 2);
width_values = C(:, 3);
for i = 1:length(I_min)
I = I1;
valid_I = I(I >= I_min(i));
valid_t = t_values(I >= I_min(i));
valid_height = height_values(I >= I_min(i));
valid_width = width_values(I >= I_min(i));
% Calculate weight using the provided weight function
weight = weightFunc(valid_t, valid_height, valid_width, l, density(i));
[min_weight, min_index] = min(weight);
optimal_I = valid_I(min_index);
optimal_t = valid_t(min_index);
optimal_height = valid_height(min_index);
optimal_width = valid_width(min_index);
disp([‘For I_min = ‘, num2str(I_min(i))]);
disp([‘Minimum weight: ‘, num2str(min_weight)]);
disp([‘Optimal valid_I: ‘, num2str(optimal_I)]);
disp([‘Minimum thickness: ‘, num2str(optimal_t)]);
disp([‘Optimal height: ‘, num2str(optimal_height)]);
disp([‘Optimal width: ‘, num2str(optimal_width)]);
disp(‘—————————————‘);
end
endI am doing a project to practice matlab and thought it would be best to be put into a function. This is my function and the rest of my code, I have variables t_values, height_values, and width_values that need to be used outside of the function, but I do not know how to use them from inside the function. These equations are going to be different for the different beams which is why I decided to create a general function. Thanks!
l = 70*12; %length
maxHeight = 12; %maximum height of beam
maxWidth = 10; %maximum width of beam
minHeight = 3; %minimum height of beam
minWidth = 3; %minimum width of beam
maxDef = 10; %maximum beam deformation
w = 3; %distributed load
p = 500; %point force
a = l/3; %distance to point force
E_alum = 9.9*10^6; %aluminum stiffness
E_steel = 28*10^6; %steel stiffness
E_ti = 16*10^6; %titanium stiffness
den_alum = .098; %aluminum density
den_steel = .286; %steel density
den_ti = .16; %titanium density
E = [E_alum, E_steel, E_ti];
density = [den_alum, den_steel, den_ti];
%For combined load
I_min = (w*(l^4)./(E.*30.*maxDef))…
– ((p*(a^2)*((3*l)-a))./(E.*6.*maxDef));
disp(‘I-Beam’);
A_horizI = width_values.*t_values; %Area of flanges
A_vertI = t_values.*(height_values-(2.*t_values)); %Area of web
I_horizI = width_values.*t_values.^3; %Moment of flanges
I_vertI = (t_values.*(height_values-(2.*t_values)).^3)./12; %Moment of web
I_I_beam = I_vertI + 2.*(I_horizI + A_horizI.*((height_values./2)-(t_values./2)).^2); %I for I beam
weightIbeam = @(t, h, w, l, density) (2*w.*t + t.*(h-2.*t))*l*density; %Weight equation for I beam
beamoptimize(I_min, l, density,I_I_beam,weightIbeam);
function beamoptimize( I_min, l, density, I1, weightFunc)
t = 0.1:0.05:1;
height = minHeight:0.05:maxHeight;
width = minWidth:0.05:maxWidth;
V = {t, height, width};
C = cell(1, numel(V));
[C{:}] = ndgrid(V{:});
C = cellfun(@(X) reshape(X, [], 1), C, ‘UniformOutput’, false);
C = horzcat(C{:});
t_values = C(:, 1);
height_values = C(:, 2);
width_values = C(:, 3);
for i = 1:length(I_min)
I = I1;
valid_I = I(I >= I_min(i));
valid_t = t_values(I >= I_min(i));
valid_height = height_values(I >= I_min(i));
valid_width = width_values(I >= I_min(i));
% Calculate weight using the provided weight function
weight = weightFunc(valid_t, valid_height, valid_width, l, density(i));
[min_weight, min_index] = min(weight);
optimal_I = valid_I(min_index);
optimal_t = valid_t(min_index);
optimal_height = valid_height(min_index);
optimal_width = valid_width(min_index);
disp([‘For I_min = ‘, num2str(I_min(i))]);
disp([‘Minimum weight: ‘, num2str(min_weight)]);
disp([‘Optimal valid_I: ‘, num2str(optimal_I)]);
disp([‘Minimum thickness: ‘, num2str(optimal_t)]);
disp([‘Optimal height: ‘, num2str(optimal_height)]);
disp([‘Optimal width: ‘, num2str(optimal_width)]);
disp(‘—————————————‘);
end
end I am doing a project to practice matlab and thought it would be best to be put into a function. This is my function and the rest of my code, I have variables t_values, height_values, and width_values that need to be used outside of the function, but I do not know how to use them from inside the function. These equations are going to be different for the different beams which is why I decided to create a general function. Thanks!
l = 70*12; %length
maxHeight = 12; %maximum height of beam
maxWidth = 10; %maximum width of beam
minHeight = 3; %minimum height of beam
minWidth = 3; %minimum width of beam
maxDef = 10; %maximum beam deformation
w = 3; %distributed load
p = 500; %point force
a = l/3; %distance to point force
E_alum = 9.9*10^6; %aluminum stiffness
E_steel = 28*10^6; %steel stiffness
E_ti = 16*10^6; %titanium stiffness
den_alum = .098; %aluminum density
den_steel = .286; %steel density
den_ti = .16; %titanium density
E = [E_alum, E_steel, E_ti];
density = [den_alum, den_steel, den_ti];
%For combined load
I_min = (w*(l^4)./(E.*30.*maxDef))…
– ((p*(a^2)*((3*l)-a))./(E.*6.*maxDef));
disp(‘I-Beam’);
A_horizI = width_values.*t_values; %Area of flanges
A_vertI = t_values.*(height_values-(2.*t_values)); %Area of web
I_horizI = width_values.*t_values.^3; %Moment of flanges
I_vertI = (t_values.*(height_values-(2.*t_values)).^3)./12; %Moment of web
I_I_beam = I_vertI + 2.*(I_horizI + A_horizI.*((height_values./2)-(t_values./2)).^2); %I for I beam
weightIbeam = @(t, h, w, l, density) (2*w.*t + t.*(h-2.*t))*l*density; %Weight equation for I beam
beamoptimize(I_min, l, density,I_I_beam,weightIbeam);
function beamoptimize( I_min, l, density, I1, weightFunc)
t = 0.1:0.05:1;
height = minHeight:0.05:maxHeight;
width = minWidth:0.05:maxWidth;
V = {t, height, width};
C = cell(1, numel(V));
[C{:}] = ndgrid(V{:});
C = cellfun(@(X) reshape(X, [], 1), C, ‘UniformOutput’, false);
C = horzcat(C{:});
t_values = C(:, 1);
height_values = C(:, 2);
width_values = C(:, 3);
for i = 1:length(I_min)
I = I1;
valid_I = I(I >= I_min(i));
valid_t = t_values(I >= I_min(i));
valid_height = height_values(I >= I_min(i));
valid_width = width_values(I >= I_min(i));
% Calculate weight using the provided weight function
weight = weightFunc(valid_t, valid_height, valid_width, l, density(i));
[min_weight, min_index] = min(weight);
optimal_I = valid_I(min_index);
optimal_t = valid_t(min_index);
optimal_height = valid_height(min_index);
optimal_width = valid_width(min_index);
disp([‘For I_min = ‘, num2str(I_min(i))]);
disp([‘Minimum weight: ‘, num2str(min_weight)]);
disp([‘Optimal valid_I: ‘, num2str(optimal_I)]);
disp([‘Minimum thickness: ‘, num2str(optimal_t)]);
disp([‘Optimal height: ‘, num2str(optimal_height)]);
disp([‘Optimal width: ‘, num2str(optimal_width)]);
disp(‘—————————————‘);
end
end help, functions, matlab MATLAB Answers — New Questions
PDEPE solver failure (spatial discretization) ; partial differential/derivative temperature modelling
Attempting to model temperature profile of an adsorption column based on concentration profile since this determines the heat of adsorption.
This is the function:
function[c,f,s] = pdefunEB(x,t,u,dudx)
global qmax_phenol K_L_phenol kf De u_s Rep Dp epsilon rho_liq cp_AC cp_feed H_ads h alpha
C = u(1) ;
q = u(2) ;
Tf = u(3) ;
dCdx = dudx(1) ;
dqdx = dudx(2) ;
dTdx = dudx(3) ;
Ts = 298.15 ; % adsorbent temp Kelvin
qstar = ((qmax_phenol)*(K_L_phenol)*C)/(1+(K_L_phenol)*C) ;
dqdt = kf*(qstar-q) ;
c = ones(3,1) ;
f = [De*dCdx;
0;
0];
s = [-u_s*dCdx-(1-epsilon)/epsilon*rho_liq*dqdt;
dqdt;
-u_s*dTdx+(((h*alpha*(Tf-Ts)-(H_ads/cp_AC))+(H_ads/cp_feed))*(dqdt*((1-epsilon)/epsilon)))] ;
end
%% initial condition
function u0 = icfunEB(x)
u0 = [0;
0;
298.15] ;
end
%% boundary condition
function [p1,q1,pr,qr] = bcfunEB(x1,u1,xr,ur,t)
global C_phenol
C0 = C_phenol ;
p1 = [u1(1)-C0;0;-298.15] ;
q1 = [0;1;0] ;
pr = [0;0;0] ;
qr = [1;1;1] ;
end
this is where the error appears (Error using pdepe Spatial discretization has failed. Discretization supports only parabolic and elliptic equations, with flux term involving spatial derivative)
mEB = 0 ;
sol1 = pdepe(mEB,@pdefunEB,@icfunEB,@bcfunEB,x,t) ;
CEB = sol1(:,:,1) ;
qEB = sol1(:,:,2) ;
TEB = sol1(:,:,3) ;
figure(2)
T0 = 298.15 ;
Cp1 = C1(:,end)./C01 ;
plot(t,TEB,’b-‘,’LineWidth’,2)
grid on
title(‘Column Temperature’)
xlabel(‘time in minutes’)
ylabel(‘temp in kelvin’)
Heres a picture of my mathematical working before input into matlab:Attempting to model temperature profile of an adsorption column based on concentration profile since this determines the heat of adsorption.
This is the function:
function[c,f,s] = pdefunEB(x,t,u,dudx)
global qmax_phenol K_L_phenol kf De u_s Rep Dp epsilon rho_liq cp_AC cp_feed H_ads h alpha
C = u(1) ;
q = u(2) ;
Tf = u(3) ;
dCdx = dudx(1) ;
dqdx = dudx(2) ;
dTdx = dudx(3) ;
Ts = 298.15 ; % adsorbent temp Kelvin
qstar = ((qmax_phenol)*(K_L_phenol)*C)/(1+(K_L_phenol)*C) ;
dqdt = kf*(qstar-q) ;
c = ones(3,1) ;
f = [De*dCdx;
0;
0];
s = [-u_s*dCdx-(1-epsilon)/epsilon*rho_liq*dqdt;
dqdt;
-u_s*dTdx+(((h*alpha*(Tf-Ts)-(H_ads/cp_AC))+(H_ads/cp_feed))*(dqdt*((1-epsilon)/epsilon)))] ;
end
%% initial condition
function u0 = icfunEB(x)
u0 = [0;
0;
298.15] ;
end
%% boundary condition
function [p1,q1,pr,qr] = bcfunEB(x1,u1,xr,ur,t)
global C_phenol
C0 = C_phenol ;
p1 = [u1(1)-C0;0;-298.15] ;
q1 = [0;1;0] ;
pr = [0;0;0] ;
qr = [1;1;1] ;
end
this is where the error appears (Error using pdepe Spatial discretization has failed. Discretization supports only parabolic and elliptic equations, with flux term involving spatial derivative)
mEB = 0 ;
sol1 = pdepe(mEB,@pdefunEB,@icfunEB,@bcfunEB,x,t) ;
CEB = sol1(:,:,1) ;
qEB = sol1(:,:,2) ;
TEB = sol1(:,:,3) ;
figure(2)
T0 = 298.15 ;
Cp1 = C1(:,end)./C01 ;
plot(t,TEB,’b-‘,’LineWidth’,2)
grid on
title(‘Column Temperature’)
xlabel(‘time in minutes’)
ylabel(‘temp in kelvin’)
Heres a picture of my mathematical working before input into matlab: Attempting to model temperature profile of an adsorption column based on concentration profile since this determines the heat of adsorption.
This is the function:
function[c,f,s] = pdefunEB(x,t,u,dudx)
global qmax_phenol K_L_phenol kf De u_s Rep Dp epsilon rho_liq cp_AC cp_feed H_ads h alpha
C = u(1) ;
q = u(2) ;
Tf = u(3) ;
dCdx = dudx(1) ;
dqdx = dudx(2) ;
dTdx = dudx(3) ;
Ts = 298.15 ; % adsorbent temp Kelvin
qstar = ((qmax_phenol)*(K_L_phenol)*C)/(1+(K_L_phenol)*C) ;
dqdt = kf*(qstar-q) ;
c = ones(3,1) ;
f = [De*dCdx;
0;
0];
s = [-u_s*dCdx-(1-epsilon)/epsilon*rho_liq*dqdt;
dqdt;
-u_s*dTdx+(((h*alpha*(Tf-Ts)-(H_ads/cp_AC))+(H_ads/cp_feed))*(dqdt*((1-epsilon)/epsilon)))] ;
end
%% initial condition
function u0 = icfunEB(x)
u0 = [0;
0;
298.15] ;
end
%% boundary condition
function [p1,q1,pr,qr] = bcfunEB(x1,u1,xr,ur,t)
global C_phenol
C0 = C_phenol ;
p1 = [u1(1)-C0;0;-298.15] ;
q1 = [0;1;0] ;
pr = [0;0;0] ;
qr = [1;1;1] ;
end
this is where the error appears (Error using pdepe Spatial discretization has failed. Discretization supports only parabolic and elliptic equations, with flux term involving spatial derivative)
mEB = 0 ;
sol1 = pdepe(mEB,@pdefunEB,@icfunEB,@bcfunEB,x,t) ;
CEB = sol1(:,:,1) ;
qEB = sol1(:,:,2) ;
TEB = sol1(:,:,3) ;
figure(2)
T0 = 298.15 ;
Cp1 = C1(:,end)./C01 ;
plot(t,TEB,’b-‘,’LineWidth’,2)
grid on
title(‘Column Temperature’)
xlabel(‘time in minutes’)
ylabel(‘temp in kelvin’)
Heres a picture of my mathematical working before input into matlab: pdepe, partials, partialdifferentials, partialderivatives, adsorption, chemical engineering, spatial discretisation MATLAB Answers — New Questions
Why is the conditional statement not working as per the condition given?
horizon=0.3;
spacing=0.1;
length=1;
numberOfParticlesAlongX=floor(length/spacing);
numberOfParticlesInDomain=numberOfParticlesAlongX; %Number of particles in X-direction attributed to domain
xComponent(1:numberOfParticlesAlongX)=((1:numberOfParticlesAlongX)-1)*spacing; %Co-ordinate of each particle stored in xComponent
CORD=xComponent;
for i=1:numberOfParticlesInDomain
p=1;
for j=1:numberOfParticlesInDomain
if i~=j %Condition for checking undesired presence of a particle in its own neighbourhood
d=abs(CORD(i)-CORD(j)); %Distance between the two particles is stored in’d’ for comparison with the horizon value
if d<=horizon
neighbourhoodArray(i,p)=j;
p=p+1; %’p’ is incremented at every step to store only the particles within the horizon distance of a particular particle.
end
end
end
end
disp(neighbourhoodArray);
This code is part of a project on material failure modelling. I need to store all the particles (labelled as ‘j’ in the for loop) within a certain distance (lablled as ‘horizon’) from a particular particle (labelled as ‘i’ in the for loop). With the given data of horizon=0.3, spacing (between particles)=0.1, and length=1, number of particles in the domain will come out to be 10. The x-component of 1st particle is ‘0’ and that of the last one is ‘0.9’, as in the ‘xComponent’ array.
Now, with the given data, for the first particle (with CORD(1)=0), the neighbourhood particles should be those at CORD(2)=0.1 (Particle-2), CORD(3)=0.2 (Particle-3), CORD(3)=0.3 (Particle-4). But, in the neighbourhoodArray array, for the 1st particle, only Particle-2 and Particle-3 are being shown to be in the neighbourhood of Particle-1, which is incorrect.
I ran the code statement-by-statement using ‘Step’ and found that the compiler is not executing the statement under "if d<=horizon" when ‘d’ and ‘horizon’ have the same value (=0.3). I really don’t understand what the problem is with the conditional statement, as I think the logic that I have used is correct.horizon=0.3;
spacing=0.1;
length=1;
numberOfParticlesAlongX=floor(length/spacing);
numberOfParticlesInDomain=numberOfParticlesAlongX; %Number of particles in X-direction attributed to domain
xComponent(1:numberOfParticlesAlongX)=((1:numberOfParticlesAlongX)-1)*spacing; %Co-ordinate of each particle stored in xComponent
CORD=xComponent;
for i=1:numberOfParticlesInDomain
p=1;
for j=1:numberOfParticlesInDomain
if i~=j %Condition for checking undesired presence of a particle in its own neighbourhood
d=abs(CORD(i)-CORD(j)); %Distance between the two particles is stored in’d’ for comparison with the horizon value
if d<=horizon
neighbourhoodArray(i,p)=j;
p=p+1; %’p’ is incremented at every step to store only the particles within the horizon distance of a particular particle.
end
end
end
end
disp(neighbourhoodArray);
This code is part of a project on material failure modelling. I need to store all the particles (labelled as ‘j’ in the for loop) within a certain distance (lablled as ‘horizon’) from a particular particle (labelled as ‘i’ in the for loop). With the given data of horizon=0.3, spacing (between particles)=0.1, and length=1, number of particles in the domain will come out to be 10. The x-component of 1st particle is ‘0’ and that of the last one is ‘0.9’, as in the ‘xComponent’ array.
Now, with the given data, for the first particle (with CORD(1)=0), the neighbourhood particles should be those at CORD(2)=0.1 (Particle-2), CORD(3)=0.2 (Particle-3), CORD(3)=0.3 (Particle-4). But, in the neighbourhoodArray array, for the 1st particle, only Particle-2 and Particle-3 are being shown to be in the neighbourhood of Particle-1, which is incorrect.
I ran the code statement-by-statement using ‘Step’ and found that the compiler is not executing the statement under "if d<=horizon" when ‘d’ and ‘horizon’ have the same value (=0.3). I really don’t understand what the problem is with the conditional statement, as I think the logic that I have used is correct. horizon=0.3;
spacing=0.1;
length=1;
numberOfParticlesAlongX=floor(length/spacing);
numberOfParticlesInDomain=numberOfParticlesAlongX; %Number of particles in X-direction attributed to domain
xComponent(1:numberOfParticlesAlongX)=((1:numberOfParticlesAlongX)-1)*spacing; %Co-ordinate of each particle stored in xComponent
CORD=xComponent;
for i=1:numberOfParticlesInDomain
p=1;
for j=1:numberOfParticlesInDomain
if i~=j %Condition for checking undesired presence of a particle in its own neighbourhood
d=abs(CORD(i)-CORD(j)); %Distance between the two particles is stored in’d’ for comparison with the horizon value
if d<=horizon
neighbourhoodArray(i,p)=j;
p=p+1; %’p’ is incremented at every step to store only the particles within the horizon distance of a particular particle.
end
end
end
end
disp(neighbourhoodArray);
This code is part of a project on material failure modelling. I need to store all the particles (labelled as ‘j’ in the for loop) within a certain distance (lablled as ‘horizon’) from a particular particle (labelled as ‘i’ in the for loop). With the given data of horizon=0.3, spacing (between particles)=0.1, and length=1, number of particles in the domain will come out to be 10. The x-component of 1st particle is ‘0’ and that of the last one is ‘0.9’, as in the ‘xComponent’ array.
Now, with the given data, for the first particle (with CORD(1)=0), the neighbourhood particles should be those at CORD(2)=0.1 (Particle-2), CORD(3)=0.2 (Particle-3), CORD(3)=0.3 (Particle-4). But, in the neighbourhoodArray array, for the 1st particle, only Particle-2 and Particle-3 are being shown to be in the neighbourhood of Particle-1, which is incorrect.
I ran the code statement-by-statement using ‘Step’ and found that the compiler is not executing the statement under "if d<=horizon" when ‘d’ and ‘horizon’ have the same value (=0.3). I really don’t understand what the problem is with the conditional statement, as I think the logic that I have used is correct. matlab, conditional statement, array MATLAB Answers — New Questions
How to put conditions to find peaks in NDVI time series?
I am using following matlab code
findpeaks(data,days’MinPeakProminence’,60)
xlabel(‘days’)
ylabel(‘NDVI’)
title(‘Find Prominent Peaks’) here the data is NDVI time series attached here.I am using following matlab code
findpeaks(data,days’MinPeakProminence’,60)
xlabel(‘days’)
ylabel(‘NDVI’)
title(‘Find Prominent Peaks’) here the data is NDVI time series attached here. I am using following matlab code
findpeaks(data,days’MinPeakProminence’,60)
xlabel(‘days’)
ylabel(‘NDVI’)
title(‘Find Prominent Peaks’) here the data is NDVI time series attached here. how to put conditions for finding peaks? MATLAB Answers — New Questions
backtestStrategy: rebalance function keeps track of past & current open position
Hi All,
backtestStrategy provides a great workflow for defining a strategy, which includes the rebalancing function.
As part of the EngineData object, WeightsHistory can be used to derive open positions, entry price and open pnl. Nonetheless … the same computation takes place also within the backtestEngine’s runBacktest function, which provides access to a Positions table for each strategy.
Hoping not having to re-invent the wheel, is there a way to pass the Positions table into the rebalancing function, for a given strategy? This would be a good fit for an additional field into the engineData structure. ThxHi All,
backtestStrategy provides a great workflow for defining a strategy, which includes the rebalancing function.
As part of the EngineData object, WeightsHistory can be used to derive open positions, entry price and open pnl. Nonetheless … the same computation takes place also within the backtestEngine’s runBacktest function, which provides access to a Positions table for each strategy.
Hoping not having to re-invent the wheel, is there a way to pass the Positions table into the rebalancing function, for a given strategy? This would be a good fit for an additional field into the engineData structure. Thx Hi All,
backtestStrategy provides a great workflow for defining a strategy, which includes the rebalancing function.
As part of the EngineData object, WeightsHistory can be used to derive open positions, entry price and open pnl. Nonetheless … the same computation takes place also within the backtestEngine’s runBacktest function, which provides access to a Positions table for each strategy.
Hoping not having to re-invent the wheel, is there a way to pass the Positions table into the rebalancing function, for a given strategy? This would be a good fit for an additional field into the engineData structure. Thx matlab, portfolio management, finance, rebalancing, backteststrategy, enginedatalist, backtestengine, runbacktest MATLAB Answers — New Questions
Display of values on Y axis
When varying data is displayed on a chart the Y axis displays value lines. If all the data in a given chart window is the same then no Y value is shown. Can this be changed please?When varying data is displayed on a chart the Y axis displays value lines. If all the data in a given chart window is the same then no Y value is shown. Can this be changed please? When varying data is displayed on a chart the Y axis displays value lines. If all the data in a given chart window is the same then no Y value is shown. Can this be changed please? thingspeak MATLAB Answers — New Questions
Decision Branching, modification Script
Modify the script so that the plotting code on lines 4-7 are executed only when doPlot is 1.
plot(density)
title("Sample Densities")
xticklabels(element)
ylabel("Density (g/cm^3)")Modify the script so that the plotting code on lines 4-7 are executed only when doPlot is 1.
plot(density)
title("Sample Densities")
xticklabels(element)
ylabel("Density (g/cm^3)") Modify the script so that the plotting code on lines 4-7 are executed only when doPlot is 1.
plot(density)
title("Sample Densities")
xticklabels(element)
ylabel("Density (g/cm^3)") decision MATLAB Answers — New Questions
Plot a vector with a given angle against the y-axis
Hi, so as the title states I want to simply plot a line that will make an angle I already know with the y axis, as this line will be plotted in the same figure as other graphs I want it to also be scaled such that it can be seen in these figures as the order of magnitude changes. I know that the vector will have the slope k = sin(angle)/cos(angle) (as it will always intercept the origin) but how do I plot it so that its range is covered by the whole figure. I have attached a figure that shows an example of what I’m trying to plotHi, so as the title states I want to simply plot a line that will make an angle I already know with the y axis, as this line will be plotted in the same figure as other graphs I want it to also be scaled such that it can be seen in these figures as the order of magnitude changes. I know that the vector will have the slope k = sin(angle)/cos(angle) (as it will always intercept the origin) but how do I plot it so that its range is covered by the whole figure. I have attached a figure that shows an example of what I’m trying to plot Hi, so as the title states I want to simply plot a line that will make an angle I already know with the y axis, as this line will be plotted in the same figure as other graphs I want it to also be scaled such that it can be seen in these figures as the order of magnitude changes. I know that the vector will have the slope k = sin(angle)/cos(angle) (as it will always intercept the origin) but how do I plot it so that its range is covered by the whole figure. I have attached a figure that shows an example of what I’m trying to plot vectors, plotting MATLAB Answers — New Questions