Category: Matlab
Category Archives: Matlab
How to choose one between two constraint conditions
clear;clc;
x = optimvar(‘x’,1,1,’LowerBound’,0)
prob=optimproblem;
prob.Constraints.con1=x<=10 or prob.Constraints.con1=x^2<=10
[sol,faval,exit]=solve(prob,’Solver’,’ga’)clear;clc;
x = optimvar(‘x’,1,1,’LowerBound’,0)
prob=optimproblem;
prob.Constraints.con1=x<=10 or prob.Constraints.con1=x^2<=10
[sol,faval,exit]=solve(prob,’Solver’,’ga’) clear;clc;
x = optimvar(‘x’,1,1,’LowerBound’,0)
prob=optimproblem;
prob.Constraints.con1=x<=10 or prob.Constraints.con1=x^2<=10
[sol,faval,exit]=solve(prob,’Solver’,’ga’) optimization toolbox, optimization, problem based optimization, constraint MATLAB Answers — New Questions
MATLAB does not recognize STM32CubeMX
When I try to build and generate code for my model on matlab/simulink I recieve the following error:
The call to stm32_make_rtw_hook, during the entry hook generated the following error:
getSTM32CubeMxPath:PathNotFound for ‘C:Program FilesSTMicroelectronicsSTM32CubeSTM32CubeMXSTM32CubeMX.exe’
===> Install STM32CubeMX tool or Update/Apply path from: Configuration Parameters > Code Generation > STM32 Options
The build process will terminate as a result.
Caused by: getSTM32CubeMxPath:PathNotFound for ‘C:Program FilesSTMicroelectronicsSTM32CubeSTM32CubeMXSTM32CubeMX.exe’
===> Install STM32CubeMX tool or Update/Apply path from: Configuration Parameters > Code Generation > STM32 Options
Even though the path is correct MATLAB does not seem to be able to recognize the program.
I could not find anyone else who encountered the same problem. Does anyone know the solution to this? Thanks in advanceWhen I try to build and generate code for my model on matlab/simulink I recieve the following error:
The call to stm32_make_rtw_hook, during the entry hook generated the following error:
getSTM32CubeMxPath:PathNotFound for ‘C:Program FilesSTMicroelectronicsSTM32CubeSTM32CubeMXSTM32CubeMX.exe’
===> Install STM32CubeMX tool or Update/Apply path from: Configuration Parameters > Code Generation > STM32 Options
The build process will terminate as a result.
Caused by: getSTM32CubeMxPath:PathNotFound for ‘C:Program FilesSTMicroelectronicsSTM32CubeSTM32CubeMXSTM32CubeMX.exe’
===> Install STM32CubeMX tool or Update/Apply path from: Configuration Parameters > Code Generation > STM32 Options
Even though the path is correct MATLAB does not seem to be able to recognize the program.
I could not find anyone else who encountered the same problem. Does anyone know the solution to this? Thanks in advance When I try to build and generate code for my model on matlab/simulink I recieve the following error:
The call to stm32_make_rtw_hook, during the entry hook generated the following error:
getSTM32CubeMxPath:PathNotFound for ‘C:Program FilesSTMicroelectronicsSTM32CubeSTM32CubeMXSTM32CubeMX.exe’
===> Install STM32CubeMX tool or Update/Apply path from: Configuration Parameters > Code Generation > STM32 Options
The build process will terminate as a result.
Caused by: getSTM32CubeMxPath:PathNotFound for ‘C:Program FilesSTMicroelectronicsSTM32CubeSTM32CubeMXSTM32CubeMX.exe’
===> Install STM32CubeMX tool or Update/Apply path from: Configuration Parameters > Code Generation > STM32 Options
Even though the path is correct MATLAB does not seem to be able to recognize the program.
I could not find anyone else who encountered the same problem. Does anyone know the solution to this? Thanks in advance simulink, stm MATLAB Answers — New Questions
can you help me ? ı try to learn matlab for this questıon
You are required to find a root of the functions given below:
(a) Bisection method, (b) Newton’s method, (c) Secant method and (d) Fixed point
iteration method.
Calculate the true percent relative error (et) in each iteration step for each method
and plot it with respect to the iteration number. Plot all four relative errors in one graph
and comment on the comparison of these methods.
Contain the MATLAB program code you have written, plots and your comments in a
single pdf file.
Determine a true relative error (st) tolerance of 10-12 to stop the iterations and apply this
tolerance in all four methods. Note that you should first find the true root of the function
with a minimum resolution of 10-13 to calculate the true relative error. You should also
determine an appropriate interval [a,b] for the function to search for the root. An
example plot of true percent relative error for different methods is given below. Your plot
should be similar to that one. It is better to use different colours for each method.
f(1)=x^2-sinh(x)You are required to find a root of the functions given below:
(a) Bisection method, (b) Newton’s method, (c) Secant method and (d) Fixed point
iteration method.
Calculate the true percent relative error (et) in each iteration step for each method
and plot it with respect to the iteration number. Plot all four relative errors in one graph
and comment on the comparison of these methods.
Contain the MATLAB program code you have written, plots and your comments in a
single pdf file.
Determine a true relative error (st) tolerance of 10-12 to stop the iterations and apply this
tolerance in all four methods. Note that you should first find the true root of the function
with a minimum resolution of 10-13 to calculate the true relative error. You should also
determine an appropriate interval [a,b] for the function to search for the root. An
example plot of true percent relative error for different methods is given below. Your plot
should be similar to that one. It is better to use different colours for each method.
f(1)=x^2-sinh(x) You are required to find a root of the functions given below:
(a) Bisection method, (b) Newton’s method, (c) Secant method and (d) Fixed point
iteration method.
Calculate the true percent relative error (et) in each iteration step for each method
and plot it with respect to the iteration number. Plot all four relative errors in one graph
and comment on the comparison of these methods.
Contain the MATLAB program code you have written, plots and your comments in a
single pdf file.
Determine a true relative error (st) tolerance of 10-12 to stop the iterations and apply this
tolerance in all four methods. Note that you should first find the true root of the function
with a minimum resolution of 10-13 to calculate the true relative error. You should also
determine an appropriate interval [a,b] for the function to search for the root. An
example plot of true percent relative error for different methods is given below. Your plot
should be similar to that one. It is better to use different colours for each method.
f(1)=x^2-sinh(x) bisection, newton raphson, secant method, fixed iteration method MATLAB Answers — New Questions
CP210x USB to UART Bridge VCP Drivers (code 10 in windows device manger)
Greetings
I’m trying to establish communication between Digilent FPGA board with Xilinx Zynq platform and matlab for my university project. As per matlab instruction, it is required to assign USB UART connection such as Silicon Labs CP210x USB to UART Bridge or Cypress Serial. However, I’m geting code 10 in windows (8.1, 10, 11) device manager. I tried different solutions suggested in the internet but they didn’t work.
I appreciate your support to share with me what kind of computer specificaiton and windows version have been tested to have successful installation of Silicon Labs CP210x USB to UART Bridge or Cypress Serial. I have tried different computers and virtual machine but no result to install the drivers without errorsGreetings
I’m trying to establish communication between Digilent FPGA board with Xilinx Zynq platform and matlab for my university project. As per matlab instruction, it is required to assign USB UART connection such as Silicon Labs CP210x USB to UART Bridge or Cypress Serial. However, I’m geting code 10 in windows (8.1, 10, 11) device manager. I tried different solutions suggested in the internet but they didn’t work.
I appreciate your support to share with me what kind of computer specificaiton and windows version have been tested to have successful installation of Silicon Labs CP210x USB to UART Bridge or Cypress Serial. I have tried different computers and virtual machine but no result to install the drivers without errors Greetings
I’m trying to establish communication between Digilent FPGA board with Xilinx Zynq platform and matlab for my university project. As per matlab instruction, it is required to assign USB UART connection such as Silicon Labs CP210x USB to UART Bridge or Cypress Serial. However, I’m geting code 10 in windows (8.1, 10, 11) device manager. I tried different solutions suggested in the internet but they didn’t work.
I appreciate your support to share with me what kind of computer specificaiton and windows version have been tested to have successful installation of Silicon Labs CP210x USB to UART Bridge or Cypress Serial. I have tried different computers and virtual machine but no result to install the drivers without errors fpga board, xilinx zynq platform, silicon labs cp210x usb to uart bridge MATLAB Answers — New Questions
Non linear fitting with 3 independent variables
I have a dataset consisting of one dependent variable (K) and 3 independent variables (a, IL, Vf). I am trying to fit a function which could represent dependent variable with fair amount of accuracy.
I have attached the Data.mat file consisting of the dataset.
The form I am trying to fit is –
K = (A – B*IL – C*a)*(D*exp(-E*Vf))
LaTeX form:
initial guess could be – , , , ,
I want the optimised coefficients for the best fitting. How to do this in curve fitting app I was able to do 2 independent variables. I am not aware of how to do this.
Also if not this function how to find some other simple function/functional forms that could represent this data. In academic research lot of people find correlation like this.
load(‘Data.mat’);
PS – Please don’t suggest a polynomial type fit consisting of linear, square and interaction terms. As the aim is to have minimum coefficients ie simpler equation.I have a dataset consisting of one dependent variable (K) and 3 independent variables (a, IL, Vf). I am trying to fit a function which could represent dependent variable with fair amount of accuracy.
I have attached the Data.mat file consisting of the dataset.
The form I am trying to fit is –
K = (A – B*IL – C*a)*(D*exp(-E*Vf))
LaTeX form:
initial guess could be – , , , ,
I want the optimised coefficients for the best fitting. How to do this in curve fitting app I was able to do 2 independent variables. I am not aware of how to do this.
Also if not this function how to find some other simple function/functional forms that could represent this data. In academic research lot of people find correlation like this.
load(‘Data.mat’);
PS – Please don’t suggest a polynomial type fit consisting of linear, square and interaction terms. As the aim is to have minimum coefficients ie simpler equation. I have a dataset consisting of one dependent variable (K) and 3 independent variables (a, IL, Vf). I am trying to fit a function which could represent dependent variable with fair amount of accuracy.
I have attached the Data.mat file consisting of the dataset.
The form I am trying to fit is –
K = (A – B*IL – C*a)*(D*exp(-E*Vf))
LaTeX form:
initial guess could be – , , , ,
I want the optimised coefficients for the best fitting. How to do this in curve fitting app I was able to do 2 independent variables. I am not aware of how to do this.
Also if not this function how to find some other simple function/functional forms that could represent this data. In academic research lot of people find correlation like this.
load(‘Data.mat’);
PS – Please don’t suggest a polynomial type fit consisting of linear, square and interaction terms. As the aim is to have minimum coefficients ie simpler equation. curve fitting, nonlinear, correlation MATLAB Answers — New Questions
code of Plot an Ellipse
clear all
close all
clc
t = linspace(0, 2*pi, 200);
xt = r1 * cos(t) + xc;
yt = r2 * sin(t) + yc;
% aply rotation by angle theta
cot = cos(theta); sit = sin(theta);
x = xt * cot – yt * sit;
y = xt * sit – yt * cot;
% draw the curbe
plot(x, y, ‘-‘);clear all
close all
clc
t = linspace(0, 2*pi, 200);
xt = r1 * cos(t) + xc;
yt = r2 * sin(t) + yc;
% aply rotation by angle theta
cot = cos(theta); sit = sin(theta);
x = xt * cot – yt * sit;
y = xt * sit – yt * cot;
% draw the curbe
plot(x, y, ‘-‘); clear all
close all
clc
t = linspace(0, 2*pi, 200);
xt = r1 * cos(t) + xc;
yt = r2 * sin(t) + yc;
% aply rotation by angle theta
cot = cos(theta); sit = sin(theta);
x = xt * cot – yt * sit;
y = xt * sit – yt * cot;
% draw the curbe
plot(x, y, ‘-‘); ellipse MATLAB Answers — New Questions
code of Ploting circle
clear all
close all
clc
angle = linspace(0, 2*pi, 360);
x = cos(angle);
y=sin(angle);
plot(x,y)clear all
close all
clc
angle = linspace(0, 2*pi, 360);
x = cos(angle);
y=sin(angle);
plot(x,y) clear all
close all
clc
angle = linspace(0, 2*pi, 360);
x = cos(angle);
y=sin(angle);
plot(x,y) circle MATLAB Answers — New Questions
TCN model to predict continuous variable
Hello there I am trying to build a TCN machine learning model for regression purposes (to predict a continuous variable). Simialar to the example here: https://www.mathworks.com/help/deeplearning/ug/sequence-to-sequence-classification-using-1-d-convolutions.html#SeqToSeqClassificationUsing1DConvAndModelFunctionExample-11. I have time series data in which I am using 3 input features (accelrometer measuments in x,y,z directions), but instead of classifying an acitivity, I am trying to estimate/predict a continuous variable. My data is stored in a table with: Time, Accel_x, Accel_Y, Accel_Z, and Response Variable. How would I modify the code here:
numFilters = 64;
filterSize = 5;
droupoutFactor = 0.005;
numBlocks = 4;
net = dlnetwork;
layer = sequenceInputLayer(NumFeatures,Normalization="rescale-symmetric",Name="input");
net = addLayers(net,layer);
outputName = layer.Name;
for i = 1:numBlocks
dilationFactor = 2^(i-1);
layers = [
convolution1dLayer(filterSize,numFilters,DilationFactor=dilationFactor,Padding="causal",Name="conv1_"+i)
layerNormalizationLayer
spatialDropoutLayer(droupoutFactor)
convolution1dLayer(filterSize,numFilters,DilationFactor=dilationFactor,Padding="causal")
layerNormalizationLayer
reluLayer
spatialDropoutLayer(dropoutFactor)
additionLayer(2,Name="add_"+i)];
% Add and connect layers.
net = addLayers(net,layers);
net = connectLayers(net,outputName,"conv1_"+i);
% Skip connection.
if i == 1
% Include convolution in first skip connection.
layer = convolution1dLayer(1,numFilters,Name="convSkip");
net = addLayers(net,layer);
net = connectLayers(net,outputName,"convSkip");
net = connectLayers(net,"convSkip","add_" + i + "/in2");
else
net = connectLayers(net,outputName,"add_" + i + "/in2");
end
% Update layer output name.
outputName = "add_" + i;
end
layers = [
fullyConnectedLayer(numClasses,Name="fc")
softmaxLayer];
net = addLayers(net,layers);
net = connectLayers(net,outputName,"fc");
options = trainingOptions("adam", …
MaxEpochs=60, …
miniBatchSize=1, …
InputDataFormats="CTB", …
Plots="training-progress", …
Metrics="accuracy", …
Verbose=0);
net = trainnet(DataTrain,DataTrain.ResonseVariable,net,"crossentropy",options);Hello there I am trying to build a TCN machine learning model for regression purposes (to predict a continuous variable). Simialar to the example here: https://www.mathworks.com/help/deeplearning/ug/sequence-to-sequence-classification-using-1-d-convolutions.html#SeqToSeqClassificationUsing1DConvAndModelFunctionExample-11. I have time series data in which I am using 3 input features (accelrometer measuments in x,y,z directions), but instead of classifying an acitivity, I am trying to estimate/predict a continuous variable. My data is stored in a table with: Time, Accel_x, Accel_Y, Accel_Z, and Response Variable. How would I modify the code here:
numFilters = 64;
filterSize = 5;
droupoutFactor = 0.005;
numBlocks = 4;
net = dlnetwork;
layer = sequenceInputLayer(NumFeatures,Normalization="rescale-symmetric",Name="input");
net = addLayers(net,layer);
outputName = layer.Name;
for i = 1:numBlocks
dilationFactor = 2^(i-1);
layers = [
convolution1dLayer(filterSize,numFilters,DilationFactor=dilationFactor,Padding="causal",Name="conv1_"+i)
layerNormalizationLayer
spatialDropoutLayer(droupoutFactor)
convolution1dLayer(filterSize,numFilters,DilationFactor=dilationFactor,Padding="causal")
layerNormalizationLayer
reluLayer
spatialDropoutLayer(dropoutFactor)
additionLayer(2,Name="add_"+i)];
% Add and connect layers.
net = addLayers(net,layers);
net = connectLayers(net,outputName,"conv1_"+i);
% Skip connection.
if i == 1
% Include convolution in first skip connection.
layer = convolution1dLayer(1,numFilters,Name="convSkip");
net = addLayers(net,layer);
net = connectLayers(net,outputName,"convSkip");
net = connectLayers(net,"convSkip","add_" + i + "/in2");
else
net = connectLayers(net,outputName,"add_" + i + "/in2");
end
% Update layer output name.
outputName = "add_" + i;
end
layers = [
fullyConnectedLayer(numClasses,Name="fc")
softmaxLayer];
net = addLayers(net,layers);
net = connectLayers(net,outputName,"fc");
options = trainingOptions("adam", …
MaxEpochs=60, …
miniBatchSize=1, …
InputDataFormats="CTB", …
Plots="training-progress", …
Metrics="accuracy", …
Verbose=0);
net = trainnet(DataTrain,DataTrain.ResonseVariable,net,"crossentropy",options); Hello there I am trying to build a TCN machine learning model for regression purposes (to predict a continuous variable). Simialar to the example here: https://www.mathworks.com/help/deeplearning/ug/sequence-to-sequence-classification-using-1-d-convolutions.html#SeqToSeqClassificationUsing1DConvAndModelFunctionExample-11. I have time series data in which I am using 3 input features (accelrometer measuments in x,y,z directions), but instead of classifying an acitivity, I am trying to estimate/predict a continuous variable. My data is stored in a table with: Time, Accel_x, Accel_Y, Accel_Z, and Response Variable. How would I modify the code here:
numFilters = 64;
filterSize = 5;
droupoutFactor = 0.005;
numBlocks = 4;
net = dlnetwork;
layer = sequenceInputLayer(NumFeatures,Normalization="rescale-symmetric",Name="input");
net = addLayers(net,layer);
outputName = layer.Name;
for i = 1:numBlocks
dilationFactor = 2^(i-1);
layers = [
convolution1dLayer(filterSize,numFilters,DilationFactor=dilationFactor,Padding="causal",Name="conv1_"+i)
layerNormalizationLayer
spatialDropoutLayer(droupoutFactor)
convolution1dLayer(filterSize,numFilters,DilationFactor=dilationFactor,Padding="causal")
layerNormalizationLayer
reluLayer
spatialDropoutLayer(dropoutFactor)
additionLayer(2,Name="add_"+i)];
% Add and connect layers.
net = addLayers(net,layers);
net = connectLayers(net,outputName,"conv1_"+i);
% Skip connection.
if i == 1
% Include convolution in first skip connection.
layer = convolution1dLayer(1,numFilters,Name="convSkip");
net = addLayers(net,layer);
net = connectLayers(net,outputName,"convSkip");
net = connectLayers(net,"convSkip","add_" + i + "/in2");
else
net = connectLayers(net,outputName,"add_" + i + "/in2");
end
% Update layer output name.
outputName = "add_" + i;
end
layers = [
fullyConnectedLayer(numClasses,Name="fc")
softmaxLayer];
net = addLayers(net,layers);
net = connectLayers(net,outputName,"fc");
options = trainingOptions("adam", …
MaxEpochs=60, …
miniBatchSize=1, …
InputDataFormats="CTB", …
Plots="training-progress", …
Metrics="accuracy", …
Verbose=0);
net = trainnet(DataTrain,DataTrain.ResonseVariable,net,"crossentropy",options); machine learning, neural networks, regression, model predictions MATLAB Answers — New Questions
Plot a line between two points
clear all
close all
clc
x1=2;y1=3;x2=8;y2=7;
plot([x1 x2],[y1 y2])
p = plot(1:100,’*’);
p.MarkerSize = 10;
axis([1 100 1 100])clear all
close all
clc
x1=2;y1=3;x2=8;y2=7;
plot([x1 x2],[y1 y2])
p = plot(1:100,’*’);
p.MarkerSize = 10;
axis([1 100 1 100]) clear all
close all
clc
x1=2;y1=3;x2=8;y2=7;
plot([x1 x2],[y1 y2])
p = plot(1:100,’*’);
p.MarkerSize = 10;
axis([1 100 1 100]) point MATLAB Answers — New Questions
Step input to 6DOF impacts performance
I am currently using a 6DOF block with the moment input being a sum of two signals. When one of these signals is a step input (i.e., going from zero to a nonzero value over a single timestep), the simulation slows down significantly; however, this only occurs for a moment about one axis and not about the other two axes. Are there any potential solutions for this?I am currently using a 6DOF block with the moment input being a sum of two signals. When one of these signals is a step input (i.e., going from zero to a nonzero value over a single timestep), the simulation slows down significantly; however, this only occurs for a moment about one axis and not about the other two axes. Are there any potential solutions for this? I am currently using a 6DOF block with the moment input being a sum of two signals. When one of these signals is a step input (i.e., going from zero to a nonzero value over a single timestep), the simulation slows down significantly; however, this only occurs for a moment about one axis and not about the other two axes. Are there any potential solutions for this? 6dof MATLAB Answers — New Questions
error using the g2s (grad2surf) function on R2024a
Hello all,
I have used the functions alot on version R2021b and they ran perfect.
When i tried to run it on R2024a and got an error regarding the lyap function (the function g2s calls for g2sSylvester which calls for "lyap" function on line 100).
Just to verify, I ran it again with same variables on the older version and the error disappeared.
Any idea what is causing this and how it can be solved?
As i am using the new DL functions of the later version i would like to keep using the later version
BR
NoamHello all,
I have used the functions alot on version R2021b and they ran perfect.
When i tried to run it on R2024a and got an error regarding the lyap function (the function g2s calls for g2sSylvester which calls for "lyap" function on line 100).
Just to verify, I ran it again with same variables on the older version and the error disappeared.
Any idea what is causing this and how it can be solved?
As i am using the new DL functions of the later version i would like to keep using the later version
BR
Noam Hello all,
I have used the functions alot on version R2021b and they ran perfect.
When i tried to run it on R2024a and got an error regarding the lyap function (the function g2s calls for g2sSylvester which calls for "lyap" function on line 100).
Just to verify, I ran it again with same variables on the older version and the error disappeared.
Any idea what is causing this and how it can be solved?
As i am using the new DL functions of the later version i would like to keep using the later version
BR
Noam optimization, deep learning, computer vision MATLAB Answers — New Questions
Is there a way to create a lot of graphs for a 4D matrix without coding for a ton of individual graphs?
I have a 4D matrix that I’m trying to create graphs for. There are 4 dimensions, a physical state, two informational states, and time.
I want to make a bunch of graphs within a larger "graph" Basically info state 1 on the y axis and info state 2 on the x axis, but then within that, there are a bunch of graphs with physical state on the y axis and time on the x axis.
Here’s an example of one graph:
fivexfive(:,:)=opt(:,5,5,:);
imagesc(fivexfive);
colorbar;
xlabel(‘Time’);
ylabel(‘State’);
set(gca,’YDir’,’normal’);
axis(‘square’)
the second two dimensions range from 1-15 each. So that’d be….. a lot of graphs.
Is there any way to try and make at least a few of them without brute forcing a ton of graphs? If that’s not possible that’s fine, figured I’d try asking!I have a 4D matrix that I’m trying to create graphs for. There are 4 dimensions, a physical state, two informational states, and time.
I want to make a bunch of graphs within a larger "graph" Basically info state 1 on the y axis and info state 2 on the x axis, but then within that, there are a bunch of graphs with physical state on the y axis and time on the x axis.
Here’s an example of one graph:
fivexfive(:,:)=opt(:,5,5,:);
imagesc(fivexfive);
colorbar;
xlabel(‘Time’);
ylabel(‘State’);
set(gca,’YDir’,’normal’);
axis(‘square’)
the second two dimensions range from 1-15 each. So that’d be….. a lot of graphs.
Is there any way to try and make at least a few of them without brute forcing a ton of graphs? If that’s not possible that’s fine, figured I’d try asking! I have a 4D matrix that I’m trying to create graphs for. There are 4 dimensions, a physical state, two informational states, and time.
I want to make a bunch of graphs within a larger "graph" Basically info state 1 on the y axis and info state 2 on the x axis, but then within that, there are a bunch of graphs with physical state on the y axis and time on the x axis.
Here’s an example of one graph:
fivexfive(:,:)=opt(:,5,5,:);
imagesc(fivexfive);
colorbar;
xlabel(‘Time’);
ylabel(‘State’);
set(gca,’YDir’,’normal’);
axis(‘square’)
the second two dimensions range from 1-15 each. So that’d be….. a lot of graphs.
Is there any way to try and make at least a few of them without brute forcing a ton of graphs? If that’s not possible that’s fine, figured I’d try asking! graph, 4d matrix, matrix MATLAB Answers — New Questions
solving non-linear ODE
I’m trying to solve ODE using MATLAB(ode45), but not working.
In this case, how can I modify code
Here is existing code
a = theta_m / erf(Z)/(2*sqrt(alpha * t));
c = (1 – theta_m)/(erfc(Z)/(2*sqrt(alpha * t)));
term1 = simplify(a – c);
term2 = (sqrt(pi)*rho*del_H/(2*k*(T1-T0))) * exp((Z)^2/(4*alpha^2*t^2));
dZdt = @(t,Z) term1/term2
tspan = [0 5];
Z0 = 0;
[t,Z] = ode45(dZdt, tspan, Z0);
Error using superiorfloat
Inputs must be floats, namely single or double.
Error in odearguments (line 114)
dataType = superiorfloat(t0,y0,f0);
Error in ode45 (line 107)
odearguments(odeIsFuncHandle,odeTreatAsMFile, solver_name, ode, tspan, y0, options, varargin);
Error in untitled3 (line 27)
[t,Z] = ode45(dZdt, tspan, Z0);
Thanks for your supportI’m trying to solve ODE using MATLAB(ode45), but not working.
In this case, how can I modify code
Here is existing code
a = theta_m / erf(Z)/(2*sqrt(alpha * t));
c = (1 – theta_m)/(erfc(Z)/(2*sqrt(alpha * t)));
term1 = simplify(a – c);
term2 = (sqrt(pi)*rho*del_H/(2*k*(T1-T0))) * exp((Z)^2/(4*alpha^2*t^2));
dZdt = @(t,Z) term1/term2
tspan = [0 5];
Z0 = 0;
[t,Z] = ode45(dZdt, tspan, Z0);
Error using superiorfloat
Inputs must be floats, namely single or double.
Error in odearguments (line 114)
dataType = superiorfloat(t0,y0,f0);
Error in ode45 (line 107)
odearguments(odeIsFuncHandle,odeTreatAsMFile, solver_name, ode, tspan, y0, options, varargin);
Error in untitled3 (line 27)
[t,Z] = ode45(dZdt, tspan, Z0);
Thanks for your support I’m trying to solve ODE using MATLAB(ode45), but not working.
In this case, how can I modify code
Here is existing code
a = theta_m / erf(Z)/(2*sqrt(alpha * t));
c = (1 – theta_m)/(erfc(Z)/(2*sqrt(alpha * t)));
term1 = simplify(a – c);
term2 = (sqrt(pi)*rho*del_H/(2*k*(T1-T0))) * exp((Z)^2/(4*alpha^2*t^2));
dZdt = @(t,Z) term1/term2
tspan = [0 5];
Z0 = 0;
[t,Z] = ode45(dZdt, tspan, Z0);
Error using superiorfloat
Inputs must be floats, namely single or double.
Error in odearguments (line 114)
dataType = superiorfloat(t0,y0,f0);
Error in ode45 (line 107)
odearguments(odeIsFuncHandle,odeTreatAsMFile, solver_name, ode, tspan, y0, options, varargin);
Error in untitled3 (line 27)
[t,Z] = ode45(dZdt, tspan, Z0);
Thanks for your support ode, nonlinear, matlab code MATLAB Answers — New Questions
xregion yregion back/front control
I play with the new xregion command (R2023A)
The red region is hide by the histogram, not sure why it is not as document example and what should I do to bring it in front
Data = randn(1,1000);
figure
histogram(Data,20,’Normalization’,’pdf’,’FaceColor’, ‘c’);
hold on
m = mean(Data);
s = std(Data);
x = linspace(m-3*s,m+3*s).’;
g = 1/(s*sqrt(2*pi))*exp(-(x-m).^2/(2*s^2));
plot(x,g,’c’, ‘LineWidth’, 2);
xregion(1, m+3*s,’FaceColor’, [0.5 0 0], ‘FaceAlpha’, 1)
set(gca, ‘XTick’, [], ‘YTick’, [], ‘ZTick’, [], ‘Color’, ‘k’);
Note: I play with gca Children order, it doesn’t seem to affect the front/back priority.
Ultimately what I want is this (here I use patch rather than xregion)I play with the new xregion command (R2023A)
The red region is hide by the histogram, not sure why it is not as document example and what should I do to bring it in front
Data = randn(1,1000);
figure
histogram(Data,20,’Normalization’,’pdf’,’FaceColor’, ‘c’);
hold on
m = mean(Data);
s = std(Data);
x = linspace(m-3*s,m+3*s).’;
g = 1/(s*sqrt(2*pi))*exp(-(x-m).^2/(2*s^2));
plot(x,g,’c’, ‘LineWidth’, 2);
xregion(1, m+3*s,’FaceColor’, [0.5 0 0], ‘FaceAlpha’, 1)
set(gca, ‘XTick’, [], ‘YTick’, [], ‘ZTick’, [], ‘Color’, ‘k’);
Note: I play with gca Children order, it doesn’t seem to affect the front/back priority.
Ultimately what I want is this (here I use patch rather than xregion) I play with the new xregion command (R2023A)
The red region is hide by the histogram, not sure why it is not as document example and what should I do to bring it in front
Data = randn(1,1000);
figure
histogram(Data,20,’Normalization’,’pdf’,’FaceColor’, ‘c’);
hold on
m = mean(Data);
s = std(Data);
x = linspace(m-3*s,m+3*s).’;
g = 1/(s*sqrt(2*pi))*exp(-(x-m).^2/(2*s^2));
plot(x,g,’c’, ‘LineWidth’, 2);
xregion(1, m+3*s,’FaceColor’, [0.5 0 0], ‘FaceAlpha’, 1)
set(gca, ‘XTick’, [], ‘YTick’, [], ‘ZTick’, [], ‘Color’, ‘k’);
Note: I play with gca Children order, it doesn’t seem to affect the front/back priority.
Ultimately what I want is this (here I use patch rather than xregion) xregion, yregion, front, back MATLAB Answers — New Questions
Understanding fsolve() output when number of function evaluations is exceeded
Solving a nonlinear squared system of equations using fsolve(), in a simplified manner my code looks like this:
options = (‘Display’, ‘iter’, ‘TolX’, 1e-6, ‘TolFun’, 1e-6,…
‘MaxFunEvals’,1e7,’MaxIter’,1e7);
x1 = fsolve(@(x) num_ss_Al(x), x0, options)
Now, when the maximum number of function evaluations is reached (or the number of iterations) the variable "x1" actually gets assigned a non-zero complex part vector, i.e.:
x1 =
1.0e+02 *
Columns 1 through 9
0.0214 + 0.0003i 0.0026 – 0.0000i 0.0100 + 0.0000i 0.1005 + 0.0000i 0.0004 – 0.0003i 0.0000 – 0.0001i -0.0002 – 0.0000i 0.0026 + 0.0000i 0.6752 – 0.0000i
Columns 10 through 18
0.6720 – 0.0000i 0.0097 + 0.0005i 0.0028 – 0.0002i 0.0086 + 0.0003i 0.0000 – 0.0000i 0.0025 – 0.0001i 0.0006 + 0.0000i 0.0026 – 0.0002i 0.0020 + 0.0001i
Columns 19 through 27
-0.0010 + 0.0001i 0.0051 – 0.0001i -0.0030 – 0.0001i 0.0001 – 0.0000i -0.0028 – 0.0001i -0.0045 – 0.0003i -0.0104 – 0.0003i -0.0048 + 0.0010i -0.0030 + 0.0002i
Columns 28 through 36
0.0017 + 0.0001i -0.0315 – 0.0038i 0.0100 – 0.0000i 0.0100 + 0.0000i 0.0100 + 0.0000i 0.0100 + 0.0000i 1.2980 – 0.0000i 0.0094 + 0.0000i 0.0096 + 0.0000i
Columns 37 through 45
0.0100 + 0.0000i 0.0100 + 0.0000i 0.0100 – 0.0000i 0.0107 – 0.0001i 0.0107 – 0.0001i 0.0185 – 0.0001i 0.0151 – 0.0000i 0.0273 – 0.0003i 0.0225 – 0.0001i
Columns 46 through 54
0.0191 – 0.0001i 0.0270 – 0.0004i 0.0081 + 0.0009i 0.0081 + 0.0009i -0.0002 + 0.0000i -0.0001 – 0.0000i 0.0094 + 0.0001i 0.0122 – 0.0013i 0.0106 – 0.0001i
Columns 55 through 63
0.0081 + 0.0009i 0.0003 – 0.0004i 0.0082 + 0.0001i 0.0089 – 0.0001i 0.0113 + 0.0006i 0.0005 – 0.0005i 0.0108 + 0.0006i 0.0096 + 0.0000i 0.0004 – 0.0003i
Columns 64 through 68
0.0001 – 0.0001i 0.0100 + 0.0000i 0.0135 + 0.0000i 0.0168 + 0.0000i 0.0136 – 0.0006i
What do those values correspond to given that the solver stopped prematurely? I thought first that they might be last iteration’s evaluated values, but as far as I know and as stated in documentation the solution is a real vector or array, then for me it’d not be obvious why would numbers with non-zero imaginary part be evalutated. I’d appreciate some help in understanding this, thanks!Solving a nonlinear squared system of equations using fsolve(), in a simplified manner my code looks like this:
options = (‘Display’, ‘iter’, ‘TolX’, 1e-6, ‘TolFun’, 1e-6,…
‘MaxFunEvals’,1e7,’MaxIter’,1e7);
x1 = fsolve(@(x) num_ss_Al(x), x0, options)
Now, when the maximum number of function evaluations is reached (or the number of iterations) the variable "x1" actually gets assigned a non-zero complex part vector, i.e.:
x1 =
1.0e+02 *
Columns 1 through 9
0.0214 + 0.0003i 0.0026 – 0.0000i 0.0100 + 0.0000i 0.1005 + 0.0000i 0.0004 – 0.0003i 0.0000 – 0.0001i -0.0002 – 0.0000i 0.0026 + 0.0000i 0.6752 – 0.0000i
Columns 10 through 18
0.6720 – 0.0000i 0.0097 + 0.0005i 0.0028 – 0.0002i 0.0086 + 0.0003i 0.0000 – 0.0000i 0.0025 – 0.0001i 0.0006 + 0.0000i 0.0026 – 0.0002i 0.0020 + 0.0001i
Columns 19 through 27
-0.0010 + 0.0001i 0.0051 – 0.0001i -0.0030 – 0.0001i 0.0001 – 0.0000i -0.0028 – 0.0001i -0.0045 – 0.0003i -0.0104 – 0.0003i -0.0048 + 0.0010i -0.0030 + 0.0002i
Columns 28 through 36
0.0017 + 0.0001i -0.0315 – 0.0038i 0.0100 – 0.0000i 0.0100 + 0.0000i 0.0100 + 0.0000i 0.0100 + 0.0000i 1.2980 – 0.0000i 0.0094 + 0.0000i 0.0096 + 0.0000i
Columns 37 through 45
0.0100 + 0.0000i 0.0100 + 0.0000i 0.0100 – 0.0000i 0.0107 – 0.0001i 0.0107 – 0.0001i 0.0185 – 0.0001i 0.0151 – 0.0000i 0.0273 – 0.0003i 0.0225 – 0.0001i
Columns 46 through 54
0.0191 – 0.0001i 0.0270 – 0.0004i 0.0081 + 0.0009i 0.0081 + 0.0009i -0.0002 + 0.0000i -0.0001 – 0.0000i 0.0094 + 0.0001i 0.0122 – 0.0013i 0.0106 – 0.0001i
Columns 55 through 63
0.0081 + 0.0009i 0.0003 – 0.0004i 0.0082 + 0.0001i 0.0089 – 0.0001i 0.0113 + 0.0006i 0.0005 – 0.0005i 0.0108 + 0.0006i 0.0096 + 0.0000i 0.0004 – 0.0003i
Columns 64 through 68
0.0001 – 0.0001i 0.0100 + 0.0000i 0.0135 + 0.0000i 0.0168 + 0.0000i 0.0136 – 0.0006i
What do those values correspond to given that the solver stopped prematurely? I thought first that they might be last iteration’s evaluated values, but as far as I know and as stated in documentation the solution is a real vector or array, then for me it’d not be obvious why would numbers with non-zero imaginary part be evalutated. I’d appreciate some help in understanding this, thanks! Solving a nonlinear squared system of equations using fsolve(), in a simplified manner my code looks like this:
options = (‘Display’, ‘iter’, ‘TolX’, 1e-6, ‘TolFun’, 1e-6,…
‘MaxFunEvals’,1e7,’MaxIter’,1e7);
x1 = fsolve(@(x) num_ss_Al(x), x0, options)
Now, when the maximum number of function evaluations is reached (or the number of iterations) the variable "x1" actually gets assigned a non-zero complex part vector, i.e.:
x1 =
1.0e+02 *
Columns 1 through 9
0.0214 + 0.0003i 0.0026 – 0.0000i 0.0100 + 0.0000i 0.1005 + 0.0000i 0.0004 – 0.0003i 0.0000 – 0.0001i -0.0002 – 0.0000i 0.0026 + 0.0000i 0.6752 – 0.0000i
Columns 10 through 18
0.6720 – 0.0000i 0.0097 + 0.0005i 0.0028 – 0.0002i 0.0086 + 0.0003i 0.0000 – 0.0000i 0.0025 – 0.0001i 0.0006 + 0.0000i 0.0026 – 0.0002i 0.0020 + 0.0001i
Columns 19 through 27
-0.0010 + 0.0001i 0.0051 – 0.0001i -0.0030 – 0.0001i 0.0001 – 0.0000i -0.0028 – 0.0001i -0.0045 – 0.0003i -0.0104 – 0.0003i -0.0048 + 0.0010i -0.0030 + 0.0002i
Columns 28 through 36
0.0017 + 0.0001i -0.0315 – 0.0038i 0.0100 – 0.0000i 0.0100 + 0.0000i 0.0100 + 0.0000i 0.0100 + 0.0000i 1.2980 – 0.0000i 0.0094 + 0.0000i 0.0096 + 0.0000i
Columns 37 through 45
0.0100 + 0.0000i 0.0100 + 0.0000i 0.0100 – 0.0000i 0.0107 – 0.0001i 0.0107 – 0.0001i 0.0185 – 0.0001i 0.0151 – 0.0000i 0.0273 – 0.0003i 0.0225 – 0.0001i
Columns 46 through 54
0.0191 – 0.0001i 0.0270 – 0.0004i 0.0081 + 0.0009i 0.0081 + 0.0009i -0.0002 + 0.0000i -0.0001 – 0.0000i 0.0094 + 0.0001i 0.0122 – 0.0013i 0.0106 – 0.0001i
Columns 55 through 63
0.0081 + 0.0009i 0.0003 – 0.0004i 0.0082 + 0.0001i 0.0089 – 0.0001i 0.0113 + 0.0006i 0.0005 – 0.0005i 0.0108 + 0.0006i 0.0096 + 0.0000i 0.0004 – 0.0003i
Columns 64 through 68
0.0001 – 0.0001i 0.0100 + 0.0000i 0.0135 + 0.0000i 0.0168 + 0.0000i 0.0136 – 0.0006i
What do those values correspond to given that the solver stopped prematurely? I thought first that they might be last iteration’s evaluated values, but as far as I know and as stated in documentation the solution is a real vector or array, then for me it’d not be obvious why would numbers with non-zero imaginary part be evalutated. I’d appreciate some help in understanding this, thanks! fsolve MATLAB Answers — New Questions
Why Simulink Embedded Coder Reusable functions are generated in Class private section
Hi all,
In simulink 2023 i have subsystem defined as resuble function. After code generation this function goes to class private member functions section. I want to use function for other areas/codes. Is there any way create reusable function outside of class?
*2018 version this reusable function created in <modelName>_private.h header file. Can we do same thing in 2023?Hi all,
In simulink 2023 i have subsystem defined as resuble function. After code generation this function goes to class private member functions section. I want to use function for other areas/codes. Is there any way create reusable function outside of class?
*2018 version this reusable function created in <modelName>_private.h header file. Can we do same thing in 2023? Hi all,
In simulink 2023 i have subsystem defined as resuble function. After code generation this function goes to class private member functions section. I want to use function for other areas/codes. Is there any way create reusable function outside of class?
*2018 version this reusable function created in <modelName>_private.h header file. Can we do same thing in 2023? simulink, code generation, c++ MATLAB Answers — New Questions
How do I plot 14th and 86th percentile?
Here I am currently running Bayesian time varying model in matlab and this is my whole code. I am not sure how can I create 14th and 86th percentile of my posterior distribution/credible interval that I have found using gibbs sampling and carter kohn algorithm. Furthermore, how do I plot the 14th and 86th percentile along with my mean posterior distribution in one graph?
clear;
% Load data from Excel file
Cyclicalitydata = readtable("Could be final data set.xlsx");
Countrydata = Cyclicalitydata(strcmp(Cyclicalitydata.Country, ‘Netherlands’), :);
% Prepare variables
Fiscalvariable = Countrydata.CAPB1; % Dependent variable, original series
LaggedFiscalvariable = [NaN; Fiscalvariable(1:end-1)]; % Creating one-period lag
Economicactivity = Countrydata.Outputgap; % Independent main variable
Govsize = Countrydata.Govsize; % Control variable 1
Debtp = Countrydata.DebtGDP; % Control variable 2
CPIlevel = Countrydata.CPIlevel; % Additional control variable 3
Years = Countrydata.Year; % Year for plotting and analysis
CPIgrowth = [NaN; CPIlevel(1:end-1)];
% Define the state-space model components
T = numel(LaggedFiscalvariable); % Number of observations, using the lagged variable now
C = [Economicactivity, Govsize, Debtp, CPIgrowth]; % Each row of C corresponds to an observation time
N = size(C,2);
A = eye(N); % Assuming independent evolution of each coefficient
Q = 0.01 * eye(N); % Small variance to assume minor changes over time
R = 1; % Observation noise variance
% Calculate OLS estimates for initialization
validIdx = ~isnan(LaggedFiscalvariable) & ~any(isnan(C), 2);
C_valid = C(validIdx, :);
Y_valid = LaggedFiscalvariable(validIdx);
beta_OLS = (C_valid’ * C_valid) (C_valid’ * Y_valid);
residuals = Y_valid – C_valid * beta_OLS;
sigma2_OLS = residuals’ * residuals / (length(Y_valid) – size(C_valid, 2));
% Initialize beta_0 and V_0 with OLS estimates
beta_0 = beta_OLS; % Use OLS estimates as initial states
V_0 = sigma2_OLS * eye(N); % Scale identity matrix by OLS residual variance
% Number of Gibbs sampling iterations
numIterations = 1000;
beta_samples = zeros(N, T, numIterations); % Store samples of all beta coefficients
% Gibbs Sampling Loop
for iter = 1:numIterations
% Run the Carter-Kohn algorithm for the current iteration
[beta_t, ~] = carterKohn(LaggedFiscalvariable, A, C, Q, R, beta_0, V_0, T);
% Store the sample
beta_samples(:, :, iter) = beta_t;
end
% Post-processing after Gibbs sampling
% Focus on the OutputGap coefficient’s estimates and its posterior distribution
burn_in = 100;
posterior_beta_outputgap = squeeze(mean(beta_samples(1, :, burn_in:end), 3));
% Plot only the OutputGap coefficient estimates over years
figure;
plot(Years, posterior_beta_outputgap, ‘LineWidth’, 2);
title(‘Posterior Estimates of OutputGap Coefficient over Years for the Netherlands’);
xlabel(‘Year’);
ylabel(‘Coefficient for OutputGap’);
function [beta_t, V_t] = carterKohn(Y, A, C, Q, R, beta_0, V_0, T)
n = size(A, 1); % Number of coefficients
beta_t = zeros(n, T);
V_t = zeros(n, n, T);
beta_pred = beta_0;
V_pred = V_0;
for t = 1:T
if isnan(Y(t))
continue; % Skip iterations where Y is NaN
end
% Observation update
C_t = C(t, :); % Current row of C
y_pred = C_t * beta_pred;
S = C_t * V_pred * C_t’ + R;
K = V_pred * C_t’ / S;
beta_t(:, t) = beta_pred + K * (Y(t) – y_pred);
V_t(:, :, t) = (eye(n) – K * C_t) * V_pred;
% Time update
if t < T
beta_pred = A * beta_t(:, t);
V_pred = A * V_t(:, :, t) * A’ + Q;
end
end
endHere I am currently running Bayesian time varying model in matlab and this is my whole code. I am not sure how can I create 14th and 86th percentile of my posterior distribution/credible interval that I have found using gibbs sampling and carter kohn algorithm. Furthermore, how do I plot the 14th and 86th percentile along with my mean posterior distribution in one graph?
clear;
% Load data from Excel file
Cyclicalitydata = readtable("Could be final data set.xlsx");
Countrydata = Cyclicalitydata(strcmp(Cyclicalitydata.Country, ‘Netherlands’), :);
% Prepare variables
Fiscalvariable = Countrydata.CAPB1; % Dependent variable, original series
LaggedFiscalvariable = [NaN; Fiscalvariable(1:end-1)]; % Creating one-period lag
Economicactivity = Countrydata.Outputgap; % Independent main variable
Govsize = Countrydata.Govsize; % Control variable 1
Debtp = Countrydata.DebtGDP; % Control variable 2
CPIlevel = Countrydata.CPIlevel; % Additional control variable 3
Years = Countrydata.Year; % Year for plotting and analysis
CPIgrowth = [NaN; CPIlevel(1:end-1)];
% Define the state-space model components
T = numel(LaggedFiscalvariable); % Number of observations, using the lagged variable now
C = [Economicactivity, Govsize, Debtp, CPIgrowth]; % Each row of C corresponds to an observation time
N = size(C,2);
A = eye(N); % Assuming independent evolution of each coefficient
Q = 0.01 * eye(N); % Small variance to assume minor changes over time
R = 1; % Observation noise variance
% Calculate OLS estimates for initialization
validIdx = ~isnan(LaggedFiscalvariable) & ~any(isnan(C), 2);
C_valid = C(validIdx, :);
Y_valid = LaggedFiscalvariable(validIdx);
beta_OLS = (C_valid’ * C_valid) (C_valid’ * Y_valid);
residuals = Y_valid – C_valid * beta_OLS;
sigma2_OLS = residuals’ * residuals / (length(Y_valid) – size(C_valid, 2));
% Initialize beta_0 and V_0 with OLS estimates
beta_0 = beta_OLS; % Use OLS estimates as initial states
V_0 = sigma2_OLS * eye(N); % Scale identity matrix by OLS residual variance
% Number of Gibbs sampling iterations
numIterations = 1000;
beta_samples = zeros(N, T, numIterations); % Store samples of all beta coefficients
% Gibbs Sampling Loop
for iter = 1:numIterations
% Run the Carter-Kohn algorithm for the current iteration
[beta_t, ~] = carterKohn(LaggedFiscalvariable, A, C, Q, R, beta_0, V_0, T);
% Store the sample
beta_samples(:, :, iter) = beta_t;
end
% Post-processing after Gibbs sampling
% Focus on the OutputGap coefficient’s estimates and its posterior distribution
burn_in = 100;
posterior_beta_outputgap = squeeze(mean(beta_samples(1, :, burn_in:end), 3));
% Plot only the OutputGap coefficient estimates over years
figure;
plot(Years, posterior_beta_outputgap, ‘LineWidth’, 2);
title(‘Posterior Estimates of OutputGap Coefficient over Years for the Netherlands’);
xlabel(‘Year’);
ylabel(‘Coefficient for OutputGap’);
function [beta_t, V_t] = carterKohn(Y, A, C, Q, R, beta_0, V_0, T)
n = size(A, 1); % Number of coefficients
beta_t = zeros(n, T);
V_t = zeros(n, n, T);
beta_pred = beta_0;
V_pred = V_0;
for t = 1:T
if isnan(Y(t))
continue; % Skip iterations where Y is NaN
end
% Observation update
C_t = C(t, :); % Current row of C
y_pred = C_t * beta_pred;
S = C_t * V_pred * C_t’ + R;
K = V_pred * C_t’ / S;
beta_t(:, t) = beta_pred + K * (Y(t) – y_pred);
V_t(:, :, t) = (eye(n) – K * C_t) * V_pred;
% Time update
if t < T
beta_pred = A * beta_t(:, t);
V_pred = A * V_t(:, :, t) * A’ + Q;
end
end
end Here I am currently running Bayesian time varying model in matlab and this is my whole code. I am not sure how can I create 14th and 86th percentile of my posterior distribution/credible interval that I have found using gibbs sampling and carter kohn algorithm. Furthermore, how do I plot the 14th and 86th percentile along with my mean posterior distribution in one graph?
clear;
% Load data from Excel file
Cyclicalitydata = readtable("Could be final data set.xlsx");
Countrydata = Cyclicalitydata(strcmp(Cyclicalitydata.Country, ‘Netherlands’), :);
% Prepare variables
Fiscalvariable = Countrydata.CAPB1; % Dependent variable, original series
LaggedFiscalvariable = [NaN; Fiscalvariable(1:end-1)]; % Creating one-period lag
Economicactivity = Countrydata.Outputgap; % Independent main variable
Govsize = Countrydata.Govsize; % Control variable 1
Debtp = Countrydata.DebtGDP; % Control variable 2
CPIlevel = Countrydata.CPIlevel; % Additional control variable 3
Years = Countrydata.Year; % Year for plotting and analysis
CPIgrowth = [NaN; CPIlevel(1:end-1)];
% Define the state-space model components
T = numel(LaggedFiscalvariable); % Number of observations, using the lagged variable now
C = [Economicactivity, Govsize, Debtp, CPIgrowth]; % Each row of C corresponds to an observation time
N = size(C,2);
A = eye(N); % Assuming independent evolution of each coefficient
Q = 0.01 * eye(N); % Small variance to assume minor changes over time
R = 1; % Observation noise variance
% Calculate OLS estimates for initialization
validIdx = ~isnan(LaggedFiscalvariable) & ~any(isnan(C), 2);
C_valid = C(validIdx, :);
Y_valid = LaggedFiscalvariable(validIdx);
beta_OLS = (C_valid’ * C_valid) (C_valid’ * Y_valid);
residuals = Y_valid – C_valid * beta_OLS;
sigma2_OLS = residuals’ * residuals / (length(Y_valid) – size(C_valid, 2));
% Initialize beta_0 and V_0 with OLS estimates
beta_0 = beta_OLS; % Use OLS estimates as initial states
V_0 = sigma2_OLS * eye(N); % Scale identity matrix by OLS residual variance
% Number of Gibbs sampling iterations
numIterations = 1000;
beta_samples = zeros(N, T, numIterations); % Store samples of all beta coefficients
% Gibbs Sampling Loop
for iter = 1:numIterations
% Run the Carter-Kohn algorithm for the current iteration
[beta_t, ~] = carterKohn(LaggedFiscalvariable, A, C, Q, R, beta_0, V_0, T);
% Store the sample
beta_samples(:, :, iter) = beta_t;
end
% Post-processing after Gibbs sampling
% Focus on the OutputGap coefficient’s estimates and its posterior distribution
burn_in = 100;
posterior_beta_outputgap = squeeze(mean(beta_samples(1, :, burn_in:end), 3));
% Plot only the OutputGap coefficient estimates over years
figure;
plot(Years, posterior_beta_outputgap, ‘LineWidth’, 2);
title(‘Posterior Estimates of OutputGap Coefficient over Years for the Netherlands’);
xlabel(‘Year’);
ylabel(‘Coefficient for OutputGap’);
function [beta_t, V_t] = carterKohn(Y, A, C, Q, R, beta_0, V_0, T)
n = size(A, 1); % Number of coefficients
beta_t = zeros(n, T);
V_t = zeros(n, n, T);
beta_pred = beta_0;
V_pred = V_0;
for t = 1:T
if isnan(Y(t))
continue; % Skip iterations where Y is NaN
end
% Observation update
C_t = C(t, :); % Current row of C
y_pred = C_t * beta_pred;
S = C_t * V_pred * C_t’ + R;
K = V_pred * C_t’ / S;
beta_t(:, t) = beta_pred + K * (Y(t) – y_pred);
V_t(:, :, t) = (eye(n) – K * C_t) * V_pred;
% Time update
if t < T
beta_pred = A * beta_t(:, t);
V_pred = A * V_t(:, :, t) * A’ + Q;
end
end
end percentile, quantile, bayesian time varying coefficient, plot, credible interval MATLAB Answers — New Questions
Plotting a Multiple Category Line Graph
I am aware, that my question is probably a bit trivial but currently I struggle with the following. Is there anyone who could please give me a hint/ help me to make this plotting script work with the set of vectors, each of the length of 23 values as displayed below ?:
y1_L = [0 0 0 0 0 0 0 0 0 0 1 98 92 129 204 147 228 193 176 204 184 197 176];
y2_L = [196 192 201 155 38 212 171 145 112 131 137 107 195 153 186 149 130 173 187 214 132 190 205];
…and so on til y90_L
Currently my script works well when each vector is 4-value long but I run to many indexing errors when I tried to adapt it to accept 23-value-long vectors. I thought it would be easy, but I may need a little hint how to do it correctly.
I tried replacing
x_new=reshape(x_new,4,[])’;
with
x_new=reshape(x_new,M,[])’;
to make the script more dynamic, however the indexing errors still persist.
Thanks in advance for any help !
I am posting the full plotting script below to give you the full idea of how it looks and works now:
baseline_L = 885.625;
y1_L = [0,99,993,937];
y2_L = [994,803,986,928];
y3_L = [1004,866,981,656];
y4_L = [1075,1241,1082,885];
y5_L = [1131,1016,876,713];
y6_L = [1450,917,479,0];
y7_L = [0,0,176,0];
y8_L = [0,113,1441,782];
y9_L = [1348,1325,1034,820];
y10_L = [1291,1044,1626,635];
y11_L = [1190,1098,1202,413];
y12_L = [612,1131,1147,717];
y13_L = [515,1060,1114,411];
y14_L = [594,1199,1117,499];
y15_L = [571,1119,1044,336];
y16_L = [653,1140,1118,251];
y17_L = [832,839,1167,380];
y18_L = [757,1053,977,462];
y19_L = [996,1157,930,589];
y20_L = [648,1163,878,493];
y21_L = [831,1105,899,329];
y22_L = [537,980,1075,627];
y23_L = [850,109,511,438];
y24_L = [994,809,1015,587];
y25_L = [952,1172,832,755];
y26_L = [638,1108,1125,516];
y27_L = [747,1028,697,723];
y28_L = [915,972,737,626];
y29_L = [1050,965,963,853];
y30_L = [1047,818,1314,1135];
y31_L = [1923,2369,5,1];
y32_L = [47,99,89,189];
y33_L = [560,506,565,474];
y34_L = [468,2408,1587,648];
y35_L = [795,1060,852,434];
y36_L = [712,1387,1124,1054];
y37_L = [1452,2054,1321,1233];
y38_L = [1662,1431,1716,2703];
y39_L = [2816,3449,3061,2963];
y40_L = [1571,3028,1498,0];
y41_L = [0,0,0,0];
y42_L = [0,0,0,0];
y43_L = [0,0,0,0];
y44_L = [0,75,2163,2509];
y45_L = [3096,3256,4023,4483];
y46_L = [3914,5034,3964,4446];
y47_L = [3878,5344,4198,3577];
y48_L = [2499,2146,8475,6221];
y49_L = [7553,7427,5527,4408];
y50_L = [6025,5994,4317,3518];
y51_L = [3965,2980,4205,3093];
y52_L = [2495,3760,2701,3985];
y53_L = [3321,4737,3671,2495];
y54_L = [1770,3439,3448,2363];
y55_L = [4403,2082,2596,1183];
y56_L = [741,5151,3940,4389];
y57_L = [6314,5966,5104,3374];
y58_L = [4084,4464,3522,1918];
y59_L = [2873,2837,3235,2700];
y60_L = [3139,3570,5720,3273];
y61_L = [4589,4761,6301,3124];
y62_L = [5318,4092,6608,2952];
y63_L = [4507,5399,4488,3598];
y64_L = [3051,2377,3818,2158];
y65_L = [3253,3512,5322,3086];
y66_L = [4313,4979,6335,4526];
y67_L = [4858,5774,5007,4348];
y68_L = [3699,5814,3952,2731];
y69_L = [3697,2677,2468,2298];
y70_L = [4937,4445,5581,3829];
y71_L = [7477,6411,7668,5994];
y72_L = [7193,6375,5189,4807];
y73_L = [7672,6376,7115,3861];
y74_L = [8200,8190,7790,7055];
y75_L = [6029,8568,6788,5703];
y76_L = [3228,5185,3164,4991];
y77_L = [5106,7152,12818,8784];
y78_L = [8606,8061,8948,5186];
y79_L = [5336,6639,8553,5109];
y80_L = [5006,6047,6366,3279];
y81_L = [6716,9787,9124,5216];
y82_L = [7384,5237,9354,9008];
y83_L = [4726,6851,7351,2927];
y84_L = [4986,8428,7606,5448];
y85_L = [9119,4164,8406,3037];
y86_L = [7854,5099,5741,3204];
y87_L = [8788,2968,10813,2588];
y88_L = [5882,5748,8276,4469];
y89_L = [3040,5431,6014,6507];
y90_L = [2281,1364,0,0];
% GRAPH PLOTTING
y_values = [y1_L; y2_L; y3_L; y4_L; y5_L; y6_L; y7_L; y8_L; y9_L;…
y10_L; y11_L; y12_L; y13_L; y14_L; y15_L; y16_L; y17_L; y18_L; y19_L;…
y20_L; y21_L; y22_L; y23_L; y24_L; y25_L; y26_L; y27_L; y28_L; y29_L;…
y30_L; y31_L; y32_L; y33_L; y34_L; y35_L; y36_L; y37_L; y38_L; y39_L;…
y40_L; y41_L; y42_L; y43_L; y44_L; y45_L; y46_L; y47_L; y48_L; y49_L;…
y50_L; y51_L; y52_L; y53_L; y54_L; y55_L; y56_L; y57_L; y58_L; y59_L;…
y60_L; y61_L; y62_L; y63_L; y64_L; y65_L; y66_L; y67_L; y68_L; y69_L;…
y70_L; y71_L; y72_L; y73_L; y74_L; y75_L; y76_L; y77_L; y78_L; y79_L;…
y80_L; y81_L; y82_L; y83_L; y84_L; y85_L; y86_L; y87_L; y88_L; y89_L;…
y90_L];
[N,M] = size(y_values);
% No Drug Administration -> "#33FFD1"
% DCZ Pump -> "#4DBEEE"
% Saline Pump -> "#D95319"
% DCZ Injection -> "#D133FF"
% Saline Injection -> "#EDB120"
% GRAPH PLOTTING
colors = {"#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1",…
"#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1",…
"#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1",…
"#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1",…
"#4DBEEE", "#4DBEEE", "#4DBEEE", "#4DBEEE", "#4DBEEE", "#4DBEEE", "#D95319",…
"#D95319", "#D95319", "#D95319", "#D95319", "#D95319", "#D95319", "#EDB120", "#EDB120",…
"#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1",…
"#D133FF", "#D133FF", "#D133FF", "#D133FF", "#D133FF",…
"#33FFD1", "#33FFD1",…
"#EDB120", "#EDB120", "#EDB120", "#EDB120", "#EDB120",…
"#33FFD1", "#33FFD1",…
"#D133FF", "#D133FF", "#D133FF", "#D133FF", "#D133FF",…
"#33FFD1", "#33FFD1",…
"#EDB120", "#EDB120", "#EDB120", "#EDB120", "#EDB120",…
"#33FFD1", "#33FFD1",…
"#D133FF"};
% Define group names for legend
group_names = {‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’,…
‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’,…
‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’,…
‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’,…
‘DCZ Pump’,’DCZ Pump’, ‘DCZ Pump’,’DCZ Pump’,’DCZ Pump’,’DCZ Pump’,’DCZ Pump’,…
‘Saline Pump’,’Saline Pump’,’Saline Pump’,’Saline Pump’,’Saline Pump’,’Saline Pump’,’Saline Pump’,’Saline Pump’,…
‘No Drug Administration’,’No Drug Administration’,’No Drug Administration’,’No Drug Administration’,’No Drug Administration’,’No Drug Administration’,…
‘DCZ Injection’,’DCZ Injection’,’DCZ Injection’,’DCZ Injection’,’DCZ Injection’,…
‘No Drug Administration’,’No Drug Administration’,…
‘Saline Injection’,’Saline Injection’,’Saline Injection’,’Saline Injection’,’Saline Injection’,…
‘No Drug Administration’,’No Drug Administration’,…
‘DCZ Injection’,’DCZ Injection’,’DCZ Injection’,’DCZ Injection’,’DCZ Injection’,…
‘No Drug Administration’,’No Drug Administration’,…
‘Saline Injection’,’Saline Injection’,’Saline Injection’,’Saline Injection’,’Saline Injection’,…
‘No Drug Administration’,’No Drug Administration’,…
‘DCZ Injection’};
% Plotting
figure(3);
% Plot baseline
h(1) = plot([0.5, N+0.5], [baseline_L, baseline_L], ‘k’, ‘LineWidth’, 2); % Black line with thicker width
hold on;
% Calculate the mean for each date
mean_values = mean(y_values, 2);
% A moving average with a window size of 5
smooth_mean_values = movmean(mean_values, 5);
% Plot the smooth line
h(2) = plot(1:N, smooth_mean_values, ‘LineWidth’, 2, ‘Color’, ‘b’);
x_new=0.75:0.25:N+0.5;
x_new=reshape(x_new,4,[])’;
for i=1:length(y_values)
h(i+2) = plot(x_new(i,:),y_values(i,:),’Color’,colors{i},’Marker’,’o’,’LineStyle’,’-‘,’MarkerFaceColor’,colors{i});
end
xticks(1:N); % Placing x-axis ticks for every value
xticklabels({‘13.12’, ‘14.12.’, ‘15.12.’, ‘16.12.’, ‘17.12.’, ‘18.12.’, ‘19.12.’,…
‘20.12.’,’21.12.’,’22.12.’,’23.12.’,’24.12.’,’25.12.’,’26.12.’,…
‘27.12.’,’28.12.’,’29.12.’,’30.12.’,’31.12.’, …
‘1.1.’,’2.1.’,’3.1.’,’4.1.’,’5.1.’,’6.1.’,’7.1.’,…
‘8.1.’,’9.1.’,’10.1.’,’11.1.’,’12.1.’,’13.1.’,’14.1.’,…
‘15.1.’,’16.1.’,’17.1.’,’18.1.’,’19.1.’,’20.1.’,’21.1.’,…
‘22.1.’,’23.1.’,’24.1.’,’25.1.’,’26.1.’,’27.1.’,’28.1.’,…
‘29.1.’,’30.1.’,’31.1.’,…
‘1.2.’,’2.2.’,’3.2.’,’4.2.’,’5.2.’,’6.2.’,’7.2.’,…
‘8.2.’,’9.2.’,’10.2.’,’11.2.’,’12.2.’,’13.2.’,’14.2.’,…
‘15.2.’,’16.2.’,’17.2.’,’18.2.’,’19.2.’,’20.2.’,’21.2.’,…
‘22.2.’,’23.2.’,’24.2.’,’25.2.’,’26.2.’,’27.2.’,’28.2.’,…
‘29.2.’…
‘1.3.’,’2.3.’,’3.3.’,’4.3.’,’5.3.’,’6.3.’,’7.3.’,…
‘8.3.’,’9.3.’,’10.3.’,’11.3.’, ‘Baseline’, ‘Moving Average’});
% Add legend
group_names{end+1} = ‘Baseline’; % Add baseline to the legend
group_names{end+1} = ‘Moving Average’; % Add moving average to the legend
[ugn,idx] = unique(group_names([end-1:end 1:end-2]),’stable’);
legend(h(idx),ugn,’Location’, ‘northwest’)
% Add title and labels
title(‘IED Rate During Osmotic Pump and Injection Drug Administration (SK000918)’, ‘FontSize’, 19);
xlabel(‘Date’, ‘FontSize’, 16);
ylabel(‘6-hour IED Rate’, ‘FontSize’, 16);
hold off;I am aware, that my question is probably a bit trivial but currently I struggle with the following. Is there anyone who could please give me a hint/ help me to make this plotting script work with the set of vectors, each of the length of 23 values as displayed below ?:
y1_L = [0 0 0 0 0 0 0 0 0 0 1 98 92 129 204 147 228 193 176 204 184 197 176];
y2_L = [196 192 201 155 38 212 171 145 112 131 137 107 195 153 186 149 130 173 187 214 132 190 205];
…and so on til y90_L
Currently my script works well when each vector is 4-value long but I run to many indexing errors when I tried to adapt it to accept 23-value-long vectors. I thought it would be easy, but I may need a little hint how to do it correctly.
I tried replacing
x_new=reshape(x_new,4,[])’;
with
x_new=reshape(x_new,M,[])’;
to make the script more dynamic, however the indexing errors still persist.
Thanks in advance for any help !
I am posting the full plotting script below to give you the full idea of how it looks and works now:
baseline_L = 885.625;
y1_L = [0,99,993,937];
y2_L = [994,803,986,928];
y3_L = [1004,866,981,656];
y4_L = [1075,1241,1082,885];
y5_L = [1131,1016,876,713];
y6_L = [1450,917,479,0];
y7_L = [0,0,176,0];
y8_L = [0,113,1441,782];
y9_L = [1348,1325,1034,820];
y10_L = [1291,1044,1626,635];
y11_L = [1190,1098,1202,413];
y12_L = [612,1131,1147,717];
y13_L = [515,1060,1114,411];
y14_L = [594,1199,1117,499];
y15_L = [571,1119,1044,336];
y16_L = [653,1140,1118,251];
y17_L = [832,839,1167,380];
y18_L = [757,1053,977,462];
y19_L = [996,1157,930,589];
y20_L = [648,1163,878,493];
y21_L = [831,1105,899,329];
y22_L = [537,980,1075,627];
y23_L = [850,109,511,438];
y24_L = [994,809,1015,587];
y25_L = [952,1172,832,755];
y26_L = [638,1108,1125,516];
y27_L = [747,1028,697,723];
y28_L = [915,972,737,626];
y29_L = [1050,965,963,853];
y30_L = [1047,818,1314,1135];
y31_L = [1923,2369,5,1];
y32_L = [47,99,89,189];
y33_L = [560,506,565,474];
y34_L = [468,2408,1587,648];
y35_L = [795,1060,852,434];
y36_L = [712,1387,1124,1054];
y37_L = [1452,2054,1321,1233];
y38_L = [1662,1431,1716,2703];
y39_L = [2816,3449,3061,2963];
y40_L = [1571,3028,1498,0];
y41_L = [0,0,0,0];
y42_L = [0,0,0,0];
y43_L = [0,0,0,0];
y44_L = [0,75,2163,2509];
y45_L = [3096,3256,4023,4483];
y46_L = [3914,5034,3964,4446];
y47_L = [3878,5344,4198,3577];
y48_L = [2499,2146,8475,6221];
y49_L = [7553,7427,5527,4408];
y50_L = [6025,5994,4317,3518];
y51_L = [3965,2980,4205,3093];
y52_L = [2495,3760,2701,3985];
y53_L = [3321,4737,3671,2495];
y54_L = [1770,3439,3448,2363];
y55_L = [4403,2082,2596,1183];
y56_L = [741,5151,3940,4389];
y57_L = [6314,5966,5104,3374];
y58_L = [4084,4464,3522,1918];
y59_L = [2873,2837,3235,2700];
y60_L = [3139,3570,5720,3273];
y61_L = [4589,4761,6301,3124];
y62_L = [5318,4092,6608,2952];
y63_L = [4507,5399,4488,3598];
y64_L = [3051,2377,3818,2158];
y65_L = [3253,3512,5322,3086];
y66_L = [4313,4979,6335,4526];
y67_L = [4858,5774,5007,4348];
y68_L = [3699,5814,3952,2731];
y69_L = [3697,2677,2468,2298];
y70_L = [4937,4445,5581,3829];
y71_L = [7477,6411,7668,5994];
y72_L = [7193,6375,5189,4807];
y73_L = [7672,6376,7115,3861];
y74_L = [8200,8190,7790,7055];
y75_L = [6029,8568,6788,5703];
y76_L = [3228,5185,3164,4991];
y77_L = [5106,7152,12818,8784];
y78_L = [8606,8061,8948,5186];
y79_L = [5336,6639,8553,5109];
y80_L = [5006,6047,6366,3279];
y81_L = [6716,9787,9124,5216];
y82_L = [7384,5237,9354,9008];
y83_L = [4726,6851,7351,2927];
y84_L = [4986,8428,7606,5448];
y85_L = [9119,4164,8406,3037];
y86_L = [7854,5099,5741,3204];
y87_L = [8788,2968,10813,2588];
y88_L = [5882,5748,8276,4469];
y89_L = [3040,5431,6014,6507];
y90_L = [2281,1364,0,0];
% GRAPH PLOTTING
y_values = [y1_L; y2_L; y3_L; y4_L; y5_L; y6_L; y7_L; y8_L; y9_L;…
y10_L; y11_L; y12_L; y13_L; y14_L; y15_L; y16_L; y17_L; y18_L; y19_L;…
y20_L; y21_L; y22_L; y23_L; y24_L; y25_L; y26_L; y27_L; y28_L; y29_L;…
y30_L; y31_L; y32_L; y33_L; y34_L; y35_L; y36_L; y37_L; y38_L; y39_L;…
y40_L; y41_L; y42_L; y43_L; y44_L; y45_L; y46_L; y47_L; y48_L; y49_L;…
y50_L; y51_L; y52_L; y53_L; y54_L; y55_L; y56_L; y57_L; y58_L; y59_L;…
y60_L; y61_L; y62_L; y63_L; y64_L; y65_L; y66_L; y67_L; y68_L; y69_L;…
y70_L; y71_L; y72_L; y73_L; y74_L; y75_L; y76_L; y77_L; y78_L; y79_L;…
y80_L; y81_L; y82_L; y83_L; y84_L; y85_L; y86_L; y87_L; y88_L; y89_L;…
y90_L];
[N,M] = size(y_values);
% No Drug Administration -> "#33FFD1"
% DCZ Pump -> "#4DBEEE"
% Saline Pump -> "#D95319"
% DCZ Injection -> "#D133FF"
% Saline Injection -> "#EDB120"
% GRAPH PLOTTING
colors = {"#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1",…
"#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1",…
"#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1",…
"#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1",…
"#4DBEEE", "#4DBEEE", "#4DBEEE", "#4DBEEE", "#4DBEEE", "#4DBEEE", "#D95319",…
"#D95319", "#D95319", "#D95319", "#D95319", "#D95319", "#D95319", "#EDB120", "#EDB120",…
"#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1",…
"#D133FF", "#D133FF", "#D133FF", "#D133FF", "#D133FF",…
"#33FFD1", "#33FFD1",…
"#EDB120", "#EDB120", "#EDB120", "#EDB120", "#EDB120",…
"#33FFD1", "#33FFD1",…
"#D133FF", "#D133FF", "#D133FF", "#D133FF", "#D133FF",…
"#33FFD1", "#33FFD1",…
"#EDB120", "#EDB120", "#EDB120", "#EDB120", "#EDB120",…
"#33FFD1", "#33FFD1",…
"#D133FF"};
% Define group names for legend
group_names = {‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’,…
‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’,…
‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’,…
‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’,…
‘DCZ Pump’,’DCZ Pump’, ‘DCZ Pump’,’DCZ Pump’,’DCZ Pump’,’DCZ Pump’,’DCZ Pump’,…
‘Saline Pump’,’Saline Pump’,’Saline Pump’,’Saline Pump’,’Saline Pump’,’Saline Pump’,’Saline Pump’,’Saline Pump’,…
‘No Drug Administration’,’No Drug Administration’,’No Drug Administration’,’No Drug Administration’,’No Drug Administration’,’No Drug Administration’,…
‘DCZ Injection’,’DCZ Injection’,’DCZ Injection’,’DCZ Injection’,’DCZ Injection’,…
‘No Drug Administration’,’No Drug Administration’,…
‘Saline Injection’,’Saline Injection’,’Saline Injection’,’Saline Injection’,’Saline Injection’,…
‘No Drug Administration’,’No Drug Administration’,…
‘DCZ Injection’,’DCZ Injection’,’DCZ Injection’,’DCZ Injection’,’DCZ Injection’,…
‘No Drug Administration’,’No Drug Administration’,…
‘Saline Injection’,’Saline Injection’,’Saline Injection’,’Saline Injection’,’Saline Injection’,…
‘No Drug Administration’,’No Drug Administration’,…
‘DCZ Injection’};
% Plotting
figure(3);
% Plot baseline
h(1) = plot([0.5, N+0.5], [baseline_L, baseline_L], ‘k’, ‘LineWidth’, 2); % Black line with thicker width
hold on;
% Calculate the mean for each date
mean_values = mean(y_values, 2);
% A moving average with a window size of 5
smooth_mean_values = movmean(mean_values, 5);
% Plot the smooth line
h(2) = plot(1:N, smooth_mean_values, ‘LineWidth’, 2, ‘Color’, ‘b’);
x_new=0.75:0.25:N+0.5;
x_new=reshape(x_new,4,[])’;
for i=1:length(y_values)
h(i+2) = plot(x_new(i,:),y_values(i,:),’Color’,colors{i},’Marker’,’o’,’LineStyle’,’-‘,’MarkerFaceColor’,colors{i});
end
xticks(1:N); % Placing x-axis ticks for every value
xticklabels({‘13.12’, ‘14.12.’, ‘15.12.’, ‘16.12.’, ‘17.12.’, ‘18.12.’, ‘19.12.’,…
‘20.12.’,’21.12.’,’22.12.’,’23.12.’,’24.12.’,’25.12.’,’26.12.’,…
‘27.12.’,’28.12.’,’29.12.’,’30.12.’,’31.12.’, …
‘1.1.’,’2.1.’,’3.1.’,’4.1.’,’5.1.’,’6.1.’,’7.1.’,…
‘8.1.’,’9.1.’,’10.1.’,’11.1.’,’12.1.’,’13.1.’,’14.1.’,…
‘15.1.’,’16.1.’,’17.1.’,’18.1.’,’19.1.’,’20.1.’,’21.1.’,…
‘22.1.’,’23.1.’,’24.1.’,’25.1.’,’26.1.’,’27.1.’,’28.1.’,…
‘29.1.’,’30.1.’,’31.1.’,…
‘1.2.’,’2.2.’,’3.2.’,’4.2.’,’5.2.’,’6.2.’,’7.2.’,…
‘8.2.’,’9.2.’,’10.2.’,’11.2.’,’12.2.’,’13.2.’,’14.2.’,…
‘15.2.’,’16.2.’,’17.2.’,’18.2.’,’19.2.’,’20.2.’,’21.2.’,…
‘22.2.’,’23.2.’,’24.2.’,’25.2.’,’26.2.’,’27.2.’,’28.2.’,…
‘29.2.’…
‘1.3.’,’2.3.’,’3.3.’,’4.3.’,’5.3.’,’6.3.’,’7.3.’,…
‘8.3.’,’9.3.’,’10.3.’,’11.3.’, ‘Baseline’, ‘Moving Average’});
% Add legend
group_names{end+1} = ‘Baseline’; % Add baseline to the legend
group_names{end+1} = ‘Moving Average’; % Add moving average to the legend
[ugn,idx] = unique(group_names([end-1:end 1:end-2]),’stable’);
legend(h(idx),ugn,’Location’, ‘northwest’)
% Add title and labels
title(‘IED Rate During Osmotic Pump and Injection Drug Administration (SK000918)’, ‘FontSize’, 19);
xlabel(‘Date’, ‘FontSize’, 16);
ylabel(‘6-hour IED Rate’, ‘FontSize’, 16);
hold off; I am aware, that my question is probably a bit trivial but currently I struggle with the following. Is there anyone who could please give me a hint/ help me to make this plotting script work with the set of vectors, each of the length of 23 values as displayed below ?:
y1_L = [0 0 0 0 0 0 0 0 0 0 1 98 92 129 204 147 228 193 176 204 184 197 176];
y2_L = [196 192 201 155 38 212 171 145 112 131 137 107 195 153 186 149 130 173 187 214 132 190 205];
…and so on til y90_L
Currently my script works well when each vector is 4-value long but I run to many indexing errors when I tried to adapt it to accept 23-value-long vectors. I thought it would be easy, but I may need a little hint how to do it correctly.
I tried replacing
x_new=reshape(x_new,4,[])’;
with
x_new=reshape(x_new,M,[])’;
to make the script more dynamic, however the indexing errors still persist.
Thanks in advance for any help !
I am posting the full plotting script below to give you the full idea of how it looks and works now:
baseline_L = 885.625;
y1_L = [0,99,993,937];
y2_L = [994,803,986,928];
y3_L = [1004,866,981,656];
y4_L = [1075,1241,1082,885];
y5_L = [1131,1016,876,713];
y6_L = [1450,917,479,0];
y7_L = [0,0,176,0];
y8_L = [0,113,1441,782];
y9_L = [1348,1325,1034,820];
y10_L = [1291,1044,1626,635];
y11_L = [1190,1098,1202,413];
y12_L = [612,1131,1147,717];
y13_L = [515,1060,1114,411];
y14_L = [594,1199,1117,499];
y15_L = [571,1119,1044,336];
y16_L = [653,1140,1118,251];
y17_L = [832,839,1167,380];
y18_L = [757,1053,977,462];
y19_L = [996,1157,930,589];
y20_L = [648,1163,878,493];
y21_L = [831,1105,899,329];
y22_L = [537,980,1075,627];
y23_L = [850,109,511,438];
y24_L = [994,809,1015,587];
y25_L = [952,1172,832,755];
y26_L = [638,1108,1125,516];
y27_L = [747,1028,697,723];
y28_L = [915,972,737,626];
y29_L = [1050,965,963,853];
y30_L = [1047,818,1314,1135];
y31_L = [1923,2369,5,1];
y32_L = [47,99,89,189];
y33_L = [560,506,565,474];
y34_L = [468,2408,1587,648];
y35_L = [795,1060,852,434];
y36_L = [712,1387,1124,1054];
y37_L = [1452,2054,1321,1233];
y38_L = [1662,1431,1716,2703];
y39_L = [2816,3449,3061,2963];
y40_L = [1571,3028,1498,0];
y41_L = [0,0,0,0];
y42_L = [0,0,0,0];
y43_L = [0,0,0,0];
y44_L = [0,75,2163,2509];
y45_L = [3096,3256,4023,4483];
y46_L = [3914,5034,3964,4446];
y47_L = [3878,5344,4198,3577];
y48_L = [2499,2146,8475,6221];
y49_L = [7553,7427,5527,4408];
y50_L = [6025,5994,4317,3518];
y51_L = [3965,2980,4205,3093];
y52_L = [2495,3760,2701,3985];
y53_L = [3321,4737,3671,2495];
y54_L = [1770,3439,3448,2363];
y55_L = [4403,2082,2596,1183];
y56_L = [741,5151,3940,4389];
y57_L = [6314,5966,5104,3374];
y58_L = [4084,4464,3522,1918];
y59_L = [2873,2837,3235,2700];
y60_L = [3139,3570,5720,3273];
y61_L = [4589,4761,6301,3124];
y62_L = [5318,4092,6608,2952];
y63_L = [4507,5399,4488,3598];
y64_L = [3051,2377,3818,2158];
y65_L = [3253,3512,5322,3086];
y66_L = [4313,4979,6335,4526];
y67_L = [4858,5774,5007,4348];
y68_L = [3699,5814,3952,2731];
y69_L = [3697,2677,2468,2298];
y70_L = [4937,4445,5581,3829];
y71_L = [7477,6411,7668,5994];
y72_L = [7193,6375,5189,4807];
y73_L = [7672,6376,7115,3861];
y74_L = [8200,8190,7790,7055];
y75_L = [6029,8568,6788,5703];
y76_L = [3228,5185,3164,4991];
y77_L = [5106,7152,12818,8784];
y78_L = [8606,8061,8948,5186];
y79_L = [5336,6639,8553,5109];
y80_L = [5006,6047,6366,3279];
y81_L = [6716,9787,9124,5216];
y82_L = [7384,5237,9354,9008];
y83_L = [4726,6851,7351,2927];
y84_L = [4986,8428,7606,5448];
y85_L = [9119,4164,8406,3037];
y86_L = [7854,5099,5741,3204];
y87_L = [8788,2968,10813,2588];
y88_L = [5882,5748,8276,4469];
y89_L = [3040,5431,6014,6507];
y90_L = [2281,1364,0,0];
% GRAPH PLOTTING
y_values = [y1_L; y2_L; y3_L; y4_L; y5_L; y6_L; y7_L; y8_L; y9_L;…
y10_L; y11_L; y12_L; y13_L; y14_L; y15_L; y16_L; y17_L; y18_L; y19_L;…
y20_L; y21_L; y22_L; y23_L; y24_L; y25_L; y26_L; y27_L; y28_L; y29_L;…
y30_L; y31_L; y32_L; y33_L; y34_L; y35_L; y36_L; y37_L; y38_L; y39_L;…
y40_L; y41_L; y42_L; y43_L; y44_L; y45_L; y46_L; y47_L; y48_L; y49_L;…
y50_L; y51_L; y52_L; y53_L; y54_L; y55_L; y56_L; y57_L; y58_L; y59_L;…
y60_L; y61_L; y62_L; y63_L; y64_L; y65_L; y66_L; y67_L; y68_L; y69_L;…
y70_L; y71_L; y72_L; y73_L; y74_L; y75_L; y76_L; y77_L; y78_L; y79_L;…
y80_L; y81_L; y82_L; y83_L; y84_L; y85_L; y86_L; y87_L; y88_L; y89_L;…
y90_L];
[N,M] = size(y_values);
% No Drug Administration -> "#33FFD1"
% DCZ Pump -> "#4DBEEE"
% Saline Pump -> "#D95319"
% DCZ Injection -> "#D133FF"
% Saline Injection -> "#EDB120"
% GRAPH PLOTTING
colors = {"#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1",…
"#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1",…
"#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1",…
"#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1",…
"#4DBEEE", "#4DBEEE", "#4DBEEE", "#4DBEEE", "#4DBEEE", "#4DBEEE", "#D95319",…
"#D95319", "#D95319", "#D95319", "#D95319", "#D95319", "#D95319", "#EDB120", "#EDB120",…
"#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1", "#33FFD1",…
"#D133FF", "#D133FF", "#D133FF", "#D133FF", "#D133FF",…
"#33FFD1", "#33FFD1",…
"#EDB120", "#EDB120", "#EDB120", "#EDB120", "#EDB120",…
"#33FFD1", "#33FFD1",…
"#D133FF", "#D133FF", "#D133FF", "#D133FF", "#D133FF",…
"#33FFD1", "#33FFD1",…
"#EDB120", "#EDB120", "#EDB120", "#EDB120", "#EDB120",…
"#33FFD1", "#33FFD1",…
"#D133FF"};
% Define group names for legend
group_names = {‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’,…
‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’,…
‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’,…
‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’, ‘No Drug Administration’,…
‘DCZ Pump’,’DCZ Pump’, ‘DCZ Pump’,’DCZ Pump’,’DCZ Pump’,’DCZ Pump’,’DCZ Pump’,…
‘Saline Pump’,’Saline Pump’,’Saline Pump’,’Saline Pump’,’Saline Pump’,’Saline Pump’,’Saline Pump’,’Saline Pump’,…
‘No Drug Administration’,’No Drug Administration’,’No Drug Administration’,’No Drug Administration’,’No Drug Administration’,’No Drug Administration’,…
‘DCZ Injection’,’DCZ Injection’,’DCZ Injection’,’DCZ Injection’,’DCZ Injection’,…
‘No Drug Administration’,’No Drug Administration’,…
‘Saline Injection’,’Saline Injection’,’Saline Injection’,’Saline Injection’,’Saline Injection’,…
‘No Drug Administration’,’No Drug Administration’,…
‘DCZ Injection’,’DCZ Injection’,’DCZ Injection’,’DCZ Injection’,’DCZ Injection’,…
‘No Drug Administration’,’No Drug Administration’,…
‘Saline Injection’,’Saline Injection’,’Saline Injection’,’Saline Injection’,’Saline Injection’,…
‘No Drug Administration’,’No Drug Administration’,…
‘DCZ Injection’};
% Plotting
figure(3);
% Plot baseline
h(1) = plot([0.5, N+0.5], [baseline_L, baseline_L], ‘k’, ‘LineWidth’, 2); % Black line with thicker width
hold on;
% Calculate the mean for each date
mean_values = mean(y_values, 2);
% A moving average with a window size of 5
smooth_mean_values = movmean(mean_values, 5);
% Plot the smooth line
h(2) = plot(1:N, smooth_mean_values, ‘LineWidth’, 2, ‘Color’, ‘b’);
x_new=0.75:0.25:N+0.5;
x_new=reshape(x_new,4,[])’;
for i=1:length(y_values)
h(i+2) = plot(x_new(i,:),y_values(i,:),’Color’,colors{i},’Marker’,’o’,’LineStyle’,’-‘,’MarkerFaceColor’,colors{i});
end
xticks(1:N); % Placing x-axis ticks for every value
xticklabels({‘13.12’, ‘14.12.’, ‘15.12.’, ‘16.12.’, ‘17.12.’, ‘18.12.’, ‘19.12.’,…
‘20.12.’,’21.12.’,’22.12.’,’23.12.’,’24.12.’,’25.12.’,’26.12.’,…
‘27.12.’,’28.12.’,’29.12.’,’30.12.’,’31.12.’, …
‘1.1.’,’2.1.’,’3.1.’,’4.1.’,’5.1.’,’6.1.’,’7.1.’,…
‘8.1.’,’9.1.’,’10.1.’,’11.1.’,’12.1.’,’13.1.’,’14.1.’,…
‘15.1.’,’16.1.’,’17.1.’,’18.1.’,’19.1.’,’20.1.’,’21.1.’,…
‘22.1.’,’23.1.’,’24.1.’,’25.1.’,’26.1.’,’27.1.’,’28.1.’,…
‘29.1.’,’30.1.’,’31.1.’,…
‘1.2.’,’2.2.’,’3.2.’,’4.2.’,’5.2.’,’6.2.’,’7.2.’,…
‘8.2.’,’9.2.’,’10.2.’,’11.2.’,’12.2.’,’13.2.’,’14.2.’,…
‘15.2.’,’16.2.’,’17.2.’,’18.2.’,’19.2.’,’20.2.’,’21.2.’,…
‘22.2.’,’23.2.’,’24.2.’,’25.2.’,’26.2.’,’27.2.’,’28.2.’,…
‘29.2.’…
‘1.3.’,’2.3.’,’3.3.’,’4.3.’,’5.3.’,’6.3.’,’7.3.’,…
‘8.3.’,’9.3.’,’10.3.’,’11.3.’, ‘Baseline’, ‘Moving Average’});
% Add legend
group_names{end+1} = ‘Baseline’; % Add baseline to the legend
group_names{end+1} = ‘Moving Average’; % Add moving average to the legend
[ugn,idx] = unique(group_names([end-1:end 1:end-2]),’stable’);
legend(h(idx),ugn,’Location’, ‘northwest’)
% Add title and labels
title(‘IED Rate During Osmotic Pump and Injection Drug Administration (SK000918)’, ‘FontSize’, 19);
xlabel(‘Date’, ‘FontSize’, 16);
ylabel(‘6-hour IED Rate’, ‘FontSize’, 16);
hold off; line graph, data categories plot, category legend MATLAB Answers — New Questions
i want matlab code to find sand grain size
If sand image is given, how to find sand grain sizeIf sand image is given, how to find sand grain size If sand image is given, how to find sand grain size sand grain size MATLAB Answers — New Questions
Scatter graph trend line adjustment and outlier removal
Hi
I have produced the following plot for my sensor. At times my sensor could produce a false result while its trying to stablise, general all samples should be close to a trendline unlike the samples below. Is there any function which can correct this false samples, while plotting a scatter plot? I am aware of the various outliers functions i can use prior to the plotting of data, but was woundering if it possible while plot the trendline or manual adjust the trendline?Hi
I have produced the following plot for my sensor. At times my sensor could produce a false result while its trying to stablise, general all samples should be close to a trendline unlike the samples below. Is there any function which can correct this false samples, while plotting a scatter plot? I am aware of the various outliers functions i can use prior to the plotting of data, but was woundering if it possible while plot the trendline or manual adjust the trendline? Hi
I have produced the following plot for my sensor. At times my sensor could produce a false result while its trying to stablise, general all samples should be close to a trendline unlike the samples below. Is there any function which can correct this false samples, while plotting a scatter plot? I am aware of the various outliers functions i can use prior to the plotting of data, but was woundering if it possible while plot the trendline or manual adjust the trendline? scatter, matlab MATLAB Answers — New Questions