Category: Matlab
Category Archives: Matlab
how to fuse two png images with equal tranparency and with proper positioning in the final image?
Hello there,
I need to mix two pictures in a way so that one is placed over the other. But both should have equal transparency. Also the location of the first picture over the second should be determinable. is there any way we can do this using imfuse or any other function in MATLAB? whenevr I use this script one gets faded and is located in one of the corners which are not desirable. Can we fix this?Hello there,
I need to mix two pictures in a way so that one is placed over the other. But both should have equal transparency. Also the location of the first picture over the second should be determinable. is there any way we can do this using imfuse or any other function in MATLAB? whenevr I use this script one gets faded and is located in one of the corners which are not desirable. Can we fix this? Hello there,
I need to mix two pictures in a way so that one is placed over the other. But both should have equal transparency. Also the location of the first picture over the second should be determinable. is there any way we can do this using imfuse or any other function in MATLAB? whenevr I use this script one gets faded and is located in one of the corners which are not desirable. Can we fix this? imfuse, transparency, blend MATLAB Answers — New Questions
How to obtain the State Transition Matrix from Simscape Multibody model?
I need to include the Dynamic of the robot I’m using, imported from an URDF file, to a Extended Kalman Filter as the State Transition Function in order to estimate the states of the system. I tried to put all the simscape model inside a Simulink Function, but it brings Error1 saying I can’t put the solver configuration block (from the robot’s body tree) inside a subsystem. I came back and also tried taking the solver configuration block out of the Simulink Function and brin it in using a Connection Port, but it sends now Error2 saying all the elements of the body tree must be in the same level.
Error1: "’brazo_2dof/Simulink Function/Solver Configuration’ has been placed in the function call subsystem ‘brazo_2dof/Simulink Function’ but does not support this configuration. Move the block out of the function call subsystem."
Error2: "Connections of the Physical Network cross nonvirtual boundaries. If any blocks in a Physical Network are within a nonvirtual subsystem, then all blocks of that network must be in the same nonvirtual subsystem. Either move affected blocks out of the nonvirtual subsystem, move network blocks into exactly one nonvirtual subsystem, or reconfigure affected nonvirtual subsystems to be virtual subsystems."
How else could I include the dynamics of my system, imported from the URDF, as the StateTransitionFunction?I need to include the Dynamic of the robot I’m using, imported from an URDF file, to a Extended Kalman Filter as the State Transition Function in order to estimate the states of the system. I tried to put all the simscape model inside a Simulink Function, but it brings Error1 saying I can’t put the solver configuration block (from the robot’s body tree) inside a subsystem. I came back and also tried taking the solver configuration block out of the Simulink Function and brin it in using a Connection Port, but it sends now Error2 saying all the elements of the body tree must be in the same level.
Error1: "’brazo_2dof/Simulink Function/Solver Configuration’ has been placed in the function call subsystem ‘brazo_2dof/Simulink Function’ but does not support this configuration. Move the block out of the function call subsystem."
Error2: "Connections of the Physical Network cross nonvirtual boundaries. If any blocks in a Physical Network are within a nonvirtual subsystem, then all blocks of that network must be in the same nonvirtual subsystem. Either move affected blocks out of the nonvirtual subsystem, move network blocks into exactly one nonvirtual subsystem, or reconfigure affected nonvirtual subsystems to be virtual subsystems."
How else could I include the dynamics of my system, imported from the URDF, as the StateTransitionFunction? I need to include the Dynamic of the robot I’m using, imported from an URDF file, to a Extended Kalman Filter as the State Transition Function in order to estimate the states of the system. I tried to put all the simscape model inside a Simulink Function, but it brings Error1 saying I can’t put the solver configuration block (from the robot’s body tree) inside a subsystem. I came back and also tried taking the solver configuration block out of the Simulink Function and brin it in using a Connection Port, but it sends now Error2 saying all the elements of the body tree must be in the same level.
Error1: "’brazo_2dof/Simulink Function/Solver Configuration’ has been placed in the function call subsystem ‘brazo_2dof/Simulink Function’ but does not support this configuration. Move the block out of the function call subsystem."
Error2: "Connections of the Physical Network cross nonvirtual boundaries. If any blocks in a Physical Network are within a nonvirtual subsystem, then all blocks of that network must be in the same nonvirtual subsystem. Either move affected blocks out of the nonvirtual subsystem, move network blocks into exactly one nonvirtual subsystem, or reconfigure affected nonvirtual subsystems to be virtual subsystems."
How else could I include the dynamics of my system, imported from the URDF, as the StateTransitionFunction? simscape, extended kalman filter, state transition function, multibody, estimate states MATLAB Answers — New Questions
I want to create a following matrix using nested loops
Matrix[1,2,3,4,5;2,4,7,11,16;3,7,14,25,41] Here every row has different logic.How do I use for loop?Matrix[1,2,3,4,5;2,4,7,11,16;3,7,14,25,41] Here every row has different logic.How do I use for loop? Matrix[1,2,3,4,5;2,4,7,11,16;3,7,14,25,41] Here every row has different logic.How do I use for loop? #nestedloop #matrix MATLAB Answers — New Questions
Organization Sign-in portal not popping up
When I try to open Matlab Desktop 2024a it asks me to sign in and when i type my email it says "Sign into your organization’s portal to proceed." but there is not Organization portal popping up for me to sign inWhen I try to open Matlab Desktop 2024a it asks me to sign in and when i type my email it says "Sign into your organization’s portal to proceed." but there is not Organization portal popping up for me to sign in When I try to open Matlab Desktop 2024a it asks me to sign in and when i type my email it says "Sign into your organization’s portal to proceed." but there is not Organization portal popping up for me to sign in login, sign-in MATLAB Answers — New Questions
Extracting metrics from cellular pattern
I’m trying to determine the width, height, area, and centroid of an scaly pattern shown in the attached image. I’ve tried using a gradient filter, edge detection, (see attached images) and various other functions, but the problem is I’m not able to get the edges to meet up and complete the cell pattern to where I can discern each cell as a separate object using, say, the regionprops function. I was hoping to get some guidance as to whether there are specific functions or established pre-processing steps I need in order to get the image in this format. Thanks in advance for any help!I’m trying to determine the width, height, area, and centroid of an scaly pattern shown in the attached image. I’ve tried using a gradient filter, edge detection, (see attached images) and various other functions, but the problem is I’m not able to get the edges to meet up and complete the cell pattern to where I can discern each cell as a separate object using, say, the regionprops function. I was hoping to get some guidance as to whether there are specific functions or established pre-processing steps I need in order to get the image in this format. Thanks in advance for any help! I’m trying to determine the width, height, area, and centroid of an scaly pattern shown in the attached image. I’ve tried using a gradient filter, edge detection, (see attached images) and various other functions, but the problem is I’m not able to get the edges to meet up and complete the cell pattern to where I can discern each cell as a separate object using, say, the regionprops function. I was hoping to get some guidance as to whether there are specific functions or established pre-processing steps I need in order to get the image in this format. Thanks in advance for any help! image processing, regionprops, edge detection, image segmentation MATLAB Answers — New Questions
How to create tiledlayout grid in vertical order
Hello,
How to create tiledlayout grid in vertical order?
Let’s say I want to create a tiledlayout(3,2), matlab default order is
1 2
3 4
5 6
But I want the lay out to be:
1 4
2 5
3 6
How do I do that?
Thanks,
PingHello,
How to create tiledlayout grid in vertical order?
Let’s say I want to create a tiledlayout(3,2), matlab default order is
1 2
3 4
5 6
But I want the lay out to be:
1 4
2 5
3 6
How do I do that?
Thanks,
Ping Hello,
How to create tiledlayout grid in vertical order?
Let’s say I want to create a tiledlayout(3,2), matlab default order is
1 2
3 4
5 6
But I want the lay out to be:
1 4
2 5
3 6
How do I do that?
Thanks,
Ping tiledlayout, order MATLAB Answers — New Questions
Est-ce que possible de transformer image niveau de gris en image RGB? Si oui pouvez-vous me donner un code qui fait cette transformation.
Est-ce que possible de transformer image niveau de gris en image RGB? Si oui pouvez-vous me donner un code qui fait cette transformation.Est-ce que possible de transformer image niveau de gris en image RGB? Si oui pouvez-vous me donner un code qui fait cette transformation. Est-ce que possible de transformer image niveau de gris en image RGB? Si oui pouvez-vous me donner un code qui fait cette transformation. transformer image niveau de gris en image rgb? MATLAB Answers — New Questions
Problem with integration: there is a pole on a contour
I have a problem with calculation of the complex integral
The integrand has a pole in z=1 and z=-1 lying on the unit circle.
My code are as following:
t = @(theta) exp(1i*theta);
f = @(t) (t^2+3*t+2*1i)/(t+4)/(t-1)/(t+1);
integrand = @(theta) f(t(theta))*1i*exp(1i*theta);
integral_result = integral(integrand, 0, 2*pi, ‘ArrayValued’, true, ‘AbsTol’, 1e-12, ‘RelTol’, 1e-12);
result = (1/(2*pi*1i)) * integral_result;
I_num=result;
disp([‘numerical solution=’,num2str(I_num)])
How do i fix it…I have a problem with calculation of the complex integral
The integrand has a pole in z=1 and z=-1 lying on the unit circle.
My code are as following:
t = @(theta) exp(1i*theta);
f = @(t) (t^2+3*t+2*1i)/(t+4)/(t-1)/(t+1);
integrand = @(theta) f(t(theta))*1i*exp(1i*theta);
integral_result = integral(integrand, 0, 2*pi, ‘ArrayValued’, true, ‘AbsTol’, 1e-12, ‘RelTol’, 1e-12);
result = (1/(2*pi*1i)) * integral_result;
I_num=result;
disp([‘numerical solution=’,num2str(I_num)])
How do i fix it… I have a problem with calculation of the complex integral
The integrand has a pole in z=1 and z=-1 lying on the unit circle.
My code are as following:
t = @(theta) exp(1i*theta);
f = @(t) (t^2+3*t+2*1i)/(t+4)/(t-1)/(t+1);
integrand = @(theta) f(t(theta))*1i*exp(1i*theta);
integral_result = integral(integrand, 0, 2*pi, ‘ArrayValued’, true, ‘AbsTol’, 1e-12, ‘RelTol’, 1e-12);
result = (1/(2*pi*1i)) * integral_result;
I_num=result;
disp([‘numerical solution=’,num2str(I_num)])
How do i fix it… numerical integration, cauthy, matlab code MATLAB Answers — New Questions
Get expected DataType for Inherit:auto port
Hi,
I am trying to find out if there is a way programatically to check which is the expected data type of a port which is normally defined as Inherit:auto. The only parameter which lists the data type I know of is "OutDataTypeStr" which in such cases only says "Inherit:auto". Is there a programatic way to apply the inheritance rules and check what is the expected type for this port?Hi,
I am trying to find out if there is a way programatically to check which is the expected data type of a port which is normally defined as Inherit:auto. The only parameter which lists the data type I know of is "OutDataTypeStr" which in such cases only says "Inherit:auto". Is there a programatic way to apply the inheritance rules and check what is the expected type for this port? Hi,
I am trying to find out if there is a way programatically to check which is the expected data type of a port which is normally defined as Inherit:auto. The only parameter which lists the data type I know of is "OutDataTypeStr" which in such cases only says "Inherit:auto". Is there a programatic way to apply the inheritance rules and check what is the expected type for this port? simulink, programming MATLAB Answers — New Questions
Header files not generated
#include "rtw_continuous.h"
#include "rtw_solver.h"
these header files are not generated in MATLAB.
Is there any options to know that.#include "rtw_continuous.h"
#include "rtw_solver.h"
these header files are not generated in MATLAB.
Is there any options to know that. #include "rtw_continuous.h"
#include "rtw_solver.h"
these header files are not generated in MATLAB.
Is there any options to know that. embedded coder MATLAB Answers — New Questions
How to make an image grid for matlab
I am having some difficulty with MATLAB and would appreciate your help. I have a series of values, each of which generates a slice of a large grid that I want to create. I can use MATLAB to visualize each slice individually, but I am unable to generate the grid with all the slices. Could someone help me with this? The data I have from the images, the first line is 1,1,1,1 and goes up to 2,108,160,16
This is my objective his is one of the slices I can generate
I want help with a matlab code capable of joining all the slices into a single grid, as shown in the "objective" image.I am having some difficulty with MATLAB and would appreciate your help. I have a series of values, each of which generates a slice of a large grid that I want to create. I can use MATLAB to visualize each slice individually, but I am unable to generate the grid with all the slices. Could someone help me with this? The data I have from the images, the first line is 1,1,1,1 and goes up to 2,108,160,16
This is my objective his is one of the slices I can generate
I want help with a matlab code capable of joining all the slices into a single grid, as shown in the "objective" image. I am having some difficulty with MATLAB and would appreciate your help. I have a series of values, each of which generates a slice of a large grid that I want to create. I can use MATLAB to visualize each slice individually, but I am unable to generate the grid with all the slices. Could someone help me with this? The data I have from the images, the first line is 1,1,1,1 and goes up to 2,108,160,16
This is my objective his is one of the slices I can generate
I want help with a matlab code capable of joining all the slices into a single grid, as shown in the "objective" image. construct image MATLAB Answers — New Questions
Simulink crashes when running MEX functions created with Visual Studio 2022 17.10.4
We have been running MATLAB R2023B Update 7 with Simulink models using S-Functions built with VS 2022 17.9.0. When we updated to VS 2022 17.10.4 we starting having MATLAB crashes as soon as Simulink starts executing models with these MEX functions. Is this a known issue, and do we know if moving to Update 8 or 9 will fix it?We have been running MATLAB R2023B Update 7 with Simulink models using S-Functions built with VS 2022 17.9.0. When we updated to VS 2022 17.10.4 we starting having MATLAB crashes as soon as Simulink starts executing models with these MEX functions. Is this a known issue, and do we know if moving to Update 8 or 9 will fix it? We have been running MATLAB R2023B Update 7 with Simulink models using S-Functions built with VS 2022 17.9.0. When we updated to VS 2022 17.10.4 we starting having MATLAB crashes as soon as Simulink starts executing models with these MEX functions. Is this a known issue, and do we know if moving to Update 8 or 9 will fix it? mex, simulink MATLAB Answers — New Questions
“timeout” setting not work in webread function
Hi:
I use parallel loop to grab data using "webread" , I set up the timeout option to be 10 seconds,
options = weboptions;
options.Timeout = 10;
then use command like below:
timeCost=[];
parfor i=1:1:1e4
tic
webReadTmp=webread(command,options);
timeCost(i)=toc;
end
I use "timeCost" variable to record the time needed for each webread operation. however I notice there are some webread cost more than 30 second, which means the "timeout" setting is not working here.
is there any mistake with my command?
Thanks!
YuHi:
I use parallel loop to grab data using "webread" , I set up the timeout option to be 10 seconds,
options = weboptions;
options.Timeout = 10;
then use command like below:
timeCost=[];
parfor i=1:1:1e4
tic
webReadTmp=webread(command,options);
timeCost(i)=toc;
end
I use "timeCost" variable to record the time needed for each webread operation. however I notice there are some webread cost more than 30 second, which means the "timeout" setting is not working here.
is there any mistake with my command?
Thanks!
Yu Hi:
I use parallel loop to grab data using "webread" , I set up the timeout option to be 10 seconds,
options = weboptions;
options.Timeout = 10;
then use command like below:
timeCost=[];
parfor i=1:1:1e4
tic
webReadTmp=webread(command,options);
timeCost(i)=toc;
end
I use "timeCost" variable to record the time needed for each webread operation. however I notice there are some webread cost more than 30 second, which means the "timeout" setting is not working here.
is there any mistake with my command?
Thanks!
Yu "timeout" setting not work in webread function MATLAB Answers — New Questions
Integral2 seems to substitute non-scalar values of variable into integrand. Why?
Dear community,
I am struggling with an error that my code produces. I am trying to do a maximum-likelihood estimation (MLE). I am importing CSV data; each row is an observation and an observation is four-dimensional with column names "bad_bought", "good_bought", "bad_notbought", "good_notbought".
Each observation is assumed to have latent variables and that are drawn from a joint-normal distribution with mean and variance and and correlation . An observation’s numeric values for the four columns are given by
"bad_bought":
"good_bought":
"bad_notbought":
"good_notbought":
where the error terms are iid, normal, and have variance .
I understand that I can calculate the joint distribution of the four answers (for given ) directly. However, I want to use numerical integration, as in the code below, because the model will eventually become more complicated necessitating it.
I receive two type of error messages:
First, and this is copy-pasted below, MATLAB tells me my mvnpdf arguments do not have the right dimensions. I do not understand that. [t1, t2], mu_vec are both of dimensions 1×2, i.e., they have the same number of columns. This error disappears if I replace the first argument of mvnpdf with [20, 20] (or some other numbers). I do not understand why; should integral2 not substitute scalar values for t1 and t2?
Second, and this appears if I replace [t1,t2] with [20,20] in the argument of mvnpdf, I receive the error message telling me I cannot use "*" to multiply the normpdf values together. This suggests to me that again t1 and t2 are not scalars.
Could you help? Thank you!
% Load necessary data
data = readtable(‘df_restricted.csv’);
% Select relevant columns and convert to matrix
data_matrix = table2array(data(:, {‘bad_bought’, ‘good_bought’, ‘bad_notbought’, ‘good_notbought’}));
% Define the negative log-likelihood function
function neg_log_lik = neg_log_lik_real(params, data_matrix)
% Extract parameters
mu1 = params(1);
mu2 = params(2);
v1 = params(3);
v2 = params(4);
rho = params(5);
v = params(6);
% Mean vector
mu_vec = [mu1, mu2];
disp(size(mu_vec))
% Covariance matrix
cov_matrix = [v1, rho * sqrt(v1 * v2); rho * sqrt(v1 * v2), v2];
disp(size(cov_matrix))
log_sum = 0;
% Loop through each data point
for i = 1:size(data_matrix, 1)
% Define the integrand for 2-dimensional integration
f = @(t1, t2) ( …
mvnpdf([t1, t2], mu_vec, cov_matrix) …
* normpdf(data_matrix(i, 1) – (t1 – t2), 0, sqrt(v)) …
* normpdf(data_matrix(i, 2) – (t1 + t2), 0, sqrt(v)) …
* normpdf(data_matrix(i, 3) – (t1 + t2), 0, sqrt(v)) …
* normpdf(data_matrix(i, 4) – (t1 – t2), 0, sqrt(v)) …
);
% Before integral2 call
% Perform 2-dimensional numerical integration using integral2
pdf_value = integral2(f, -Inf, Inf, -Inf, Inf, ‘AbsTol’, 1e-6, ‘RelTol’, 1e-6);
% Take log of the result and accumulate
log_value = log(pdf_value);
log_sum = log_sum + log_value;
end
% Return negative log-likelihood
neg_log_lik = -log_sum;
end
% Set initial parameters
initial_params = [56, 11, 119, 131, -0.36, 419];
% Define the function handle for optimization
neg_log_lik_handle = @(params) neg_log_lik_real(params, data_matrix);
% Use fminunc to minimize the negative log-likelihood
options = optimoptions(‘fminunc’, ‘Algorithm’, ‘quasi-newton’, ‘MaxIterations’, 500, ‘TolFun’, 1e-8);
[estimated_params, fval, exitflag, output] = fminunc(neg_log_lik_handle, initial_params, options);
% Display the results
disp(‘Estimated parameters:’);
disp(estimated_params);
disp(‘Final log-likelihood value:’);
disp(-fval);
First error:
Error using mvnpdf (line 67)
X and MU must have the same number of columns.
Error in
Structural_Estimation>@(t1,t2)(mvnpdf([t1,t2],mu_vec,cov_matrix)*normpdf(data_matrix(i,1)-(t1-t2),0,sqrt(v))*normpdf(data_matrix(i,2)-(t1+t2),0,sqrt(v))*normpdf(data_matrix(i,3)-(t1+t2),0,sqrt(v))*normpdf(data_matrix(i,4)-(t1-t2),0,sqrt(v)))
(line 34)
mvnpdf([t1, t2], mu_vec, cov_matrix) …
First error:
Error in integral2Calc>@(y)fun(xi*ones(size(y)),y) (line 18)
@(y)fun(xi*ones(size(y)),y),y1i,y2i,opstruct.integralOptions), …
Error in integralCalc>iterateScalarValued (line 334)
fx = FUN(t);
Error in integralCalc>vadapt (line 148)
[q,errbnd] = iterateScalarValued(u,tinterval,pathlen, …
Error in integralCalc (line 113)
[q,errbnd] = vadapt(@minusInfToInfInvTransform,interval, …
Error in
integral2Calc>@(xi,y1i,y2i)integralCalc(@(y)fun(xi*ones(size(y)),y),y1i,y2i,opstruct.integralOptions)
(line 17)
innerintegral = @(x)arrayfun(@(xi,y1i,y2i)integralCalc( …
Error in
integral2Calc>@(x)arrayfun(@(xi,y1i,y2i)integralCalc(@(y)fun(xi*ones(size(y)),y),y1i,y2i,opstruct.integralOptions),x,ymin(x),ymax(x))
(line 17)
innerintegral = @(x)arrayfun(@(xi,y1i,y2i)integralCalc( …
Error in integralCalc>iterateScalarValued (line 334)
fx = FUN(t);
Error in integralCalc>vadapt (line 148)
[q,errbnd] = iterateScalarValued(u,tinterval,pathlen, …
Error in integralCalc (line 113)
[q,errbnd] = vadapt(@minusInfToInfInvTransform,interval, …
Error in integral2Calc>integral2i (line 20)
[q,errbnd] = integralCalc(innerintegral,xmin,xmax,opstruct.integralOptions);
Error in integral2Calc (line 7)
[q,errbnd] = integral2i(fun,xmin,xmax,ymin,ymax,optionstruct);
Error in integral2 (line 105)
Q = integral2Calc(fun,xmin,xmax,yminfun,ymaxfun,opstruct);
Error in Structural_Estimation>neg_log_lik_real (line 43)
pdf_value = integral2(f, -Inf, Inf, -Inf, Inf, ‘AbsTol’, 1e-6, ‘RelTol’, 1e-6);
Error in Structural_Estimation>@(params)neg_log_lik_real(params,data_matrix) (line 58)
neg_log_lik_handle = @(params) neg_log_lik_real(params, data_matrix);
Error in fminunc (line 233)
f = feval(funfcn{3},x,varargin{:});
Error in Structural_Estimation (line 62)
[estimated_params, fval, exitflag, output] = fminunc(neg_log_lik_handle, initial_params, options);
Caused by:
Failure in initial objective function evaluation. FMINUNC cannot continue.
—-
Second error:
Error using *
Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix
matches the number of rows in the second matrix. To operate on each element of the matrix
individually, use TIMES (.*) for elementwise multiplication.
Error in Structural_Estimation>@(t1,t2)(mvnpdf([20,20],mu_vec,cov_matrix)*normpdf(data_matrix(i,1)-(t1-t2),0,sqrt(v))*normpdf(data_matrix(i,2)-(t1+t2),0,sqrt(v))*normpdf(data_matrix(i,3)-(t1+t2),0,sqrt(v))*normpdf(data_matrix(i,4)-(t1-t2),0,sqrt(v))) (line 36)
* normpdf(data_matrix(i, 2) – (t1 + t2), 0, sqrt(v)) …
^
Error in integral2Calc>@(y)fun(xi*ones(size(y)),y) (line 18)
@(y)fun(xi*ones(size(y)),y),y1i,y2i,opstruct.integralOptions), …
^^^^^^^^^^^^^^^^^^^^^^^
Error in integralCalc>iterateScalarValued (line 334)
fx = FUN(t);
^^^^^^
Error in integralCalc>vadapt (line 148)
[q,errbnd] = iterateScalarValued(u,tinterval,pathlen, …
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in integralCalc (line 113)
[q,errbnd] = vadapt(@minusInfToInfInvTransform,interval, …
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in integral2Calc>@(xi,y1i,y2i)integralCalc(@(y)fun(xi*ones(size(y)),y),y1i,y2i,opstruct.integralOptions) (line 17)
innerintegral = @(x)arrayfun(@(xi,y1i,y2i)integralCalc( …
^^^^^^^^^^^^^^^^^
Error in integral2Calc>@(x)arrayfun(@(xi,y1i,y2i)integralCalc(@(y)fun(xi*ones(size(y)),y),y1i,y2i,opstruct.integralOptions),x,ymin(x),ymax(x)) (line 17)
innerintegral = @(x)arrayfun(@(xi,y1i,y2i)integralCalc( …
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in integralCalc>iterateScalarValued (line 334)
fx = FUN(t);
^^^^^^
Error in integralCalc>vadapt (line 148)
[q,errbnd] = iterateScalarValued(u,tinterval,pathlen, …
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in integralCalc (line 113)
[q,errbnd] = vadapt(@minusInfToInfInvTransform,interval, …
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in integral2Calc>integral2i (line 20)
[q,errbnd] = integralCalc(innerintegral,xmin,xmax,opstruct.integralOptions);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in integral2Calc (line 7)
[q,errbnd] = integral2i(fun,xmin,xmax,ymin,ymax,optionstruct);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in integral2 (line 105)
Q = integral2Calc(fun,xmin,xmax,yminfun,ymaxfun,opstruct);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in Structural_Estimation>neg_log_lik_real (line 43)
pdf_value = integral2(f, -Inf, Inf, -Inf, Inf, ‘AbsTol’, 1e-6, ‘RelTol’, 1e-6);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in Structural_Estimation>@(params)neg_log_lik_real(params,data_matrix) (line 58)
neg_log_lik_handle = @(params) neg_log_lik_real(params, data_matrix);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in fminunc (line 233)
f = feval(funfcn{3},x,varargin{:});
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in Structural_Estimation (line 62)
[estimated_params, fval, exitflag, output] = fminunc(neg_log_lik_handle, initial_params, options);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Caused by:
Failure in initial objective function evaluation. FMINUNC cannot continue.
Related documentationDear community,
I am struggling with an error that my code produces. I am trying to do a maximum-likelihood estimation (MLE). I am importing CSV data; each row is an observation and an observation is four-dimensional with column names "bad_bought", "good_bought", "bad_notbought", "good_notbought".
Each observation is assumed to have latent variables and that are drawn from a joint-normal distribution with mean and variance and and correlation . An observation’s numeric values for the four columns are given by
"bad_bought":
"good_bought":
"bad_notbought":
"good_notbought":
where the error terms are iid, normal, and have variance .
I understand that I can calculate the joint distribution of the four answers (for given ) directly. However, I want to use numerical integration, as in the code below, because the model will eventually become more complicated necessitating it.
I receive two type of error messages:
First, and this is copy-pasted below, MATLAB tells me my mvnpdf arguments do not have the right dimensions. I do not understand that. [t1, t2], mu_vec are both of dimensions 1×2, i.e., they have the same number of columns. This error disappears if I replace the first argument of mvnpdf with [20, 20] (or some other numbers). I do not understand why; should integral2 not substitute scalar values for t1 and t2?
Second, and this appears if I replace [t1,t2] with [20,20] in the argument of mvnpdf, I receive the error message telling me I cannot use "*" to multiply the normpdf values together. This suggests to me that again t1 and t2 are not scalars.
Could you help? Thank you!
% Load necessary data
data = readtable(‘df_restricted.csv’);
% Select relevant columns and convert to matrix
data_matrix = table2array(data(:, {‘bad_bought’, ‘good_bought’, ‘bad_notbought’, ‘good_notbought’}));
% Define the negative log-likelihood function
function neg_log_lik = neg_log_lik_real(params, data_matrix)
% Extract parameters
mu1 = params(1);
mu2 = params(2);
v1 = params(3);
v2 = params(4);
rho = params(5);
v = params(6);
% Mean vector
mu_vec = [mu1, mu2];
disp(size(mu_vec))
% Covariance matrix
cov_matrix = [v1, rho * sqrt(v1 * v2); rho * sqrt(v1 * v2), v2];
disp(size(cov_matrix))
log_sum = 0;
% Loop through each data point
for i = 1:size(data_matrix, 1)
% Define the integrand for 2-dimensional integration
f = @(t1, t2) ( …
mvnpdf([t1, t2], mu_vec, cov_matrix) …
* normpdf(data_matrix(i, 1) – (t1 – t2), 0, sqrt(v)) …
* normpdf(data_matrix(i, 2) – (t1 + t2), 0, sqrt(v)) …
* normpdf(data_matrix(i, 3) – (t1 + t2), 0, sqrt(v)) …
* normpdf(data_matrix(i, 4) – (t1 – t2), 0, sqrt(v)) …
);
% Before integral2 call
% Perform 2-dimensional numerical integration using integral2
pdf_value = integral2(f, -Inf, Inf, -Inf, Inf, ‘AbsTol’, 1e-6, ‘RelTol’, 1e-6);
% Take log of the result and accumulate
log_value = log(pdf_value);
log_sum = log_sum + log_value;
end
% Return negative log-likelihood
neg_log_lik = -log_sum;
end
% Set initial parameters
initial_params = [56, 11, 119, 131, -0.36, 419];
% Define the function handle for optimization
neg_log_lik_handle = @(params) neg_log_lik_real(params, data_matrix);
% Use fminunc to minimize the negative log-likelihood
options = optimoptions(‘fminunc’, ‘Algorithm’, ‘quasi-newton’, ‘MaxIterations’, 500, ‘TolFun’, 1e-8);
[estimated_params, fval, exitflag, output] = fminunc(neg_log_lik_handle, initial_params, options);
% Display the results
disp(‘Estimated parameters:’);
disp(estimated_params);
disp(‘Final log-likelihood value:’);
disp(-fval);
First error:
Error using mvnpdf (line 67)
X and MU must have the same number of columns.
Error in
Structural_Estimation>@(t1,t2)(mvnpdf([t1,t2],mu_vec,cov_matrix)*normpdf(data_matrix(i,1)-(t1-t2),0,sqrt(v))*normpdf(data_matrix(i,2)-(t1+t2),0,sqrt(v))*normpdf(data_matrix(i,3)-(t1+t2),0,sqrt(v))*normpdf(data_matrix(i,4)-(t1-t2),0,sqrt(v)))
(line 34)
mvnpdf([t1, t2], mu_vec, cov_matrix) …
First error:
Error in integral2Calc>@(y)fun(xi*ones(size(y)),y) (line 18)
@(y)fun(xi*ones(size(y)),y),y1i,y2i,opstruct.integralOptions), …
Error in integralCalc>iterateScalarValued (line 334)
fx = FUN(t);
Error in integralCalc>vadapt (line 148)
[q,errbnd] = iterateScalarValued(u,tinterval,pathlen, …
Error in integralCalc (line 113)
[q,errbnd] = vadapt(@minusInfToInfInvTransform,interval, …
Error in
integral2Calc>@(xi,y1i,y2i)integralCalc(@(y)fun(xi*ones(size(y)),y),y1i,y2i,opstruct.integralOptions)
(line 17)
innerintegral = @(x)arrayfun(@(xi,y1i,y2i)integralCalc( …
Error in
integral2Calc>@(x)arrayfun(@(xi,y1i,y2i)integralCalc(@(y)fun(xi*ones(size(y)),y),y1i,y2i,opstruct.integralOptions),x,ymin(x),ymax(x))
(line 17)
innerintegral = @(x)arrayfun(@(xi,y1i,y2i)integralCalc( …
Error in integralCalc>iterateScalarValued (line 334)
fx = FUN(t);
Error in integralCalc>vadapt (line 148)
[q,errbnd] = iterateScalarValued(u,tinterval,pathlen, …
Error in integralCalc (line 113)
[q,errbnd] = vadapt(@minusInfToInfInvTransform,interval, …
Error in integral2Calc>integral2i (line 20)
[q,errbnd] = integralCalc(innerintegral,xmin,xmax,opstruct.integralOptions);
Error in integral2Calc (line 7)
[q,errbnd] = integral2i(fun,xmin,xmax,ymin,ymax,optionstruct);
Error in integral2 (line 105)
Q = integral2Calc(fun,xmin,xmax,yminfun,ymaxfun,opstruct);
Error in Structural_Estimation>neg_log_lik_real (line 43)
pdf_value = integral2(f, -Inf, Inf, -Inf, Inf, ‘AbsTol’, 1e-6, ‘RelTol’, 1e-6);
Error in Structural_Estimation>@(params)neg_log_lik_real(params,data_matrix) (line 58)
neg_log_lik_handle = @(params) neg_log_lik_real(params, data_matrix);
Error in fminunc (line 233)
f = feval(funfcn{3},x,varargin{:});
Error in Structural_Estimation (line 62)
[estimated_params, fval, exitflag, output] = fminunc(neg_log_lik_handle, initial_params, options);
Caused by:
Failure in initial objective function evaluation. FMINUNC cannot continue.
—-
Second error:
Error using *
Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix
matches the number of rows in the second matrix. To operate on each element of the matrix
individually, use TIMES (.*) for elementwise multiplication.
Error in Structural_Estimation>@(t1,t2)(mvnpdf([20,20],mu_vec,cov_matrix)*normpdf(data_matrix(i,1)-(t1-t2),0,sqrt(v))*normpdf(data_matrix(i,2)-(t1+t2),0,sqrt(v))*normpdf(data_matrix(i,3)-(t1+t2),0,sqrt(v))*normpdf(data_matrix(i,4)-(t1-t2),0,sqrt(v))) (line 36)
* normpdf(data_matrix(i, 2) – (t1 + t2), 0, sqrt(v)) …
^
Error in integral2Calc>@(y)fun(xi*ones(size(y)),y) (line 18)
@(y)fun(xi*ones(size(y)),y),y1i,y2i,opstruct.integralOptions), …
^^^^^^^^^^^^^^^^^^^^^^^
Error in integralCalc>iterateScalarValued (line 334)
fx = FUN(t);
^^^^^^
Error in integralCalc>vadapt (line 148)
[q,errbnd] = iterateScalarValued(u,tinterval,pathlen, …
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in integralCalc (line 113)
[q,errbnd] = vadapt(@minusInfToInfInvTransform,interval, …
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in integral2Calc>@(xi,y1i,y2i)integralCalc(@(y)fun(xi*ones(size(y)),y),y1i,y2i,opstruct.integralOptions) (line 17)
innerintegral = @(x)arrayfun(@(xi,y1i,y2i)integralCalc( …
^^^^^^^^^^^^^^^^^
Error in integral2Calc>@(x)arrayfun(@(xi,y1i,y2i)integralCalc(@(y)fun(xi*ones(size(y)),y),y1i,y2i,opstruct.integralOptions),x,ymin(x),ymax(x)) (line 17)
innerintegral = @(x)arrayfun(@(xi,y1i,y2i)integralCalc( …
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in integralCalc>iterateScalarValued (line 334)
fx = FUN(t);
^^^^^^
Error in integralCalc>vadapt (line 148)
[q,errbnd] = iterateScalarValued(u,tinterval,pathlen, …
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in integralCalc (line 113)
[q,errbnd] = vadapt(@minusInfToInfInvTransform,interval, …
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in integral2Calc>integral2i (line 20)
[q,errbnd] = integralCalc(innerintegral,xmin,xmax,opstruct.integralOptions);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in integral2Calc (line 7)
[q,errbnd] = integral2i(fun,xmin,xmax,ymin,ymax,optionstruct);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in integral2 (line 105)
Q = integral2Calc(fun,xmin,xmax,yminfun,ymaxfun,opstruct);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in Structural_Estimation>neg_log_lik_real (line 43)
pdf_value = integral2(f, -Inf, Inf, -Inf, Inf, ‘AbsTol’, 1e-6, ‘RelTol’, 1e-6);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in Structural_Estimation>@(params)neg_log_lik_real(params,data_matrix) (line 58)
neg_log_lik_handle = @(params) neg_log_lik_real(params, data_matrix);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in fminunc (line 233)
f = feval(funfcn{3},x,varargin{:});
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in Structural_Estimation (line 62)
[estimated_params, fval, exitflag, output] = fminunc(neg_log_lik_handle, initial_params, options);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Caused by:
Failure in initial objective function evaluation. FMINUNC cannot continue.
Related documentation Dear community,
I am struggling with an error that my code produces. I am trying to do a maximum-likelihood estimation (MLE). I am importing CSV data; each row is an observation and an observation is four-dimensional with column names "bad_bought", "good_bought", "bad_notbought", "good_notbought".
Each observation is assumed to have latent variables and that are drawn from a joint-normal distribution with mean and variance and and correlation . An observation’s numeric values for the four columns are given by
"bad_bought":
"good_bought":
"bad_notbought":
"good_notbought":
where the error terms are iid, normal, and have variance .
I understand that I can calculate the joint distribution of the four answers (for given ) directly. However, I want to use numerical integration, as in the code below, because the model will eventually become more complicated necessitating it.
I receive two type of error messages:
First, and this is copy-pasted below, MATLAB tells me my mvnpdf arguments do not have the right dimensions. I do not understand that. [t1, t2], mu_vec are both of dimensions 1×2, i.e., they have the same number of columns. This error disappears if I replace the first argument of mvnpdf with [20, 20] (or some other numbers). I do not understand why; should integral2 not substitute scalar values for t1 and t2?
Second, and this appears if I replace [t1,t2] with [20,20] in the argument of mvnpdf, I receive the error message telling me I cannot use "*" to multiply the normpdf values together. This suggests to me that again t1 and t2 are not scalars.
Could you help? Thank you!
% Load necessary data
data = readtable(‘df_restricted.csv’);
% Select relevant columns and convert to matrix
data_matrix = table2array(data(:, {‘bad_bought’, ‘good_bought’, ‘bad_notbought’, ‘good_notbought’}));
% Define the negative log-likelihood function
function neg_log_lik = neg_log_lik_real(params, data_matrix)
% Extract parameters
mu1 = params(1);
mu2 = params(2);
v1 = params(3);
v2 = params(4);
rho = params(5);
v = params(6);
% Mean vector
mu_vec = [mu1, mu2];
disp(size(mu_vec))
% Covariance matrix
cov_matrix = [v1, rho * sqrt(v1 * v2); rho * sqrt(v1 * v2), v2];
disp(size(cov_matrix))
log_sum = 0;
% Loop through each data point
for i = 1:size(data_matrix, 1)
% Define the integrand for 2-dimensional integration
f = @(t1, t2) ( …
mvnpdf([t1, t2], mu_vec, cov_matrix) …
* normpdf(data_matrix(i, 1) – (t1 – t2), 0, sqrt(v)) …
* normpdf(data_matrix(i, 2) – (t1 + t2), 0, sqrt(v)) …
* normpdf(data_matrix(i, 3) – (t1 + t2), 0, sqrt(v)) …
* normpdf(data_matrix(i, 4) – (t1 – t2), 0, sqrt(v)) …
);
% Before integral2 call
% Perform 2-dimensional numerical integration using integral2
pdf_value = integral2(f, -Inf, Inf, -Inf, Inf, ‘AbsTol’, 1e-6, ‘RelTol’, 1e-6);
% Take log of the result and accumulate
log_value = log(pdf_value);
log_sum = log_sum + log_value;
end
% Return negative log-likelihood
neg_log_lik = -log_sum;
end
% Set initial parameters
initial_params = [56, 11, 119, 131, -0.36, 419];
% Define the function handle for optimization
neg_log_lik_handle = @(params) neg_log_lik_real(params, data_matrix);
% Use fminunc to minimize the negative log-likelihood
options = optimoptions(‘fminunc’, ‘Algorithm’, ‘quasi-newton’, ‘MaxIterations’, 500, ‘TolFun’, 1e-8);
[estimated_params, fval, exitflag, output] = fminunc(neg_log_lik_handle, initial_params, options);
% Display the results
disp(‘Estimated parameters:’);
disp(estimated_params);
disp(‘Final log-likelihood value:’);
disp(-fval);
First error:
Error using mvnpdf (line 67)
X and MU must have the same number of columns.
Error in
Structural_Estimation>@(t1,t2)(mvnpdf([t1,t2],mu_vec,cov_matrix)*normpdf(data_matrix(i,1)-(t1-t2),0,sqrt(v))*normpdf(data_matrix(i,2)-(t1+t2),0,sqrt(v))*normpdf(data_matrix(i,3)-(t1+t2),0,sqrt(v))*normpdf(data_matrix(i,4)-(t1-t2),0,sqrt(v)))
(line 34)
mvnpdf([t1, t2], mu_vec, cov_matrix) …
First error:
Error in integral2Calc>@(y)fun(xi*ones(size(y)),y) (line 18)
@(y)fun(xi*ones(size(y)),y),y1i,y2i,opstruct.integralOptions), …
Error in integralCalc>iterateScalarValued (line 334)
fx = FUN(t);
Error in integralCalc>vadapt (line 148)
[q,errbnd] = iterateScalarValued(u,tinterval,pathlen, …
Error in integralCalc (line 113)
[q,errbnd] = vadapt(@minusInfToInfInvTransform,interval, …
Error in
integral2Calc>@(xi,y1i,y2i)integralCalc(@(y)fun(xi*ones(size(y)),y),y1i,y2i,opstruct.integralOptions)
(line 17)
innerintegral = @(x)arrayfun(@(xi,y1i,y2i)integralCalc( …
Error in
integral2Calc>@(x)arrayfun(@(xi,y1i,y2i)integralCalc(@(y)fun(xi*ones(size(y)),y),y1i,y2i,opstruct.integralOptions),x,ymin(x),ymax(x))
(line 17)
innerintegral = @(x)arrayfun(@(xi,y1i,y2i)integralCalc( …
Error in integralCalc>iterateScalarValued (line 334)
fx = FUN(t);
Error in integralCalc>vadapt (line 148)
[q,errbnd] = iterateScalarValued(u,tinterval,pathlen, …
Error in integralCalc (line 113)
[q,errbnd] = vadapt(@minusInfToInfInvTransform,interval, …
Error in integral2Calc>integral2i (line 20)
[q,errbnd] = integralCalc(innerintegral,xmin,xmax,opstruct.integralOptions);
Error in integral2Calc (line 7)
[q,errbnd] = integral2i(fun,xmin,xmax,ymin,ymax,optionstruct);
Error in integral2 (line 105)
Q = integral2Calc(fun,xmin,xmax,yminfun,ymaxfun,opstruct);
Error in Structural_Estimation>neg_log_lik_real (line 43)
pdf_value = integral2(f, -Inf, Inf, -Inf, Inf, ‘AbsTol’, 1e-6, ‘RelTol’, 1e-6);
Error in Structural_Estimation>@(params)neg_log_lik_real(params,data_matrix) (line 58)
neg_log_lik_handle = @(params) neg_log_lik_real(params, data_matrix);
Error in fminunc (line 233)
f = feval(funfcn{3},x,varargin{:});
Error in Structural_Estimation (line 62)
[estimated_params, fval, exitflag, output] = fminunc(neg_log_lik_handle, initial_params, options);
Caused by:
Failure in initial objective function evaluation. FMINUNC cannot continue.
—-
Second error:
Error using *
Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix
matches the number of rows in the second matrix. To operate on each element of the matrix
individually, use TIMES (.*) for elementwise multiplication.
Error in Structural_Estimation>@(t1,t2)(mvnpdf([20,20],mu_vec,cov_matrix)*normpdf(data_matrix(i,1)-(t1-t2),0,sqrt(v))*normpdf(data_matrix(i,2)-(t1+t2),0,sqrt(v))*normpdf(data_matrix(i,3)-(t1+t2),0,sqrt(v))*normpdf(data_matrix(i,4)-(t1-t2),0,sqrt(v))) (line 36)
* normpdf(data_matrix(i, 2) – (t1 + t2), 0, sqrt(v)) …
^
Error in integral2Calc>@(y)fun(xi*ones(size(y)),y) (line 18)
@(y)fun(xi*ones(size(y)),y),y1i,y2i,opstruct.integralOptions), …
^^^^^^^^^^^^^^^^^^^^^^^
Error in integralCalc>iterateScalarValued (line 334)
fx = FUN(t);
^^^^^^
Error in integralCalc>vadapt (line 148)
[q,errbnd] = iterateScalarValued(u,tinterval,pathlen, …
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in integralCalc (line 113)
[q,errbnd] = vadapt(@minusInfToInfInvTransform,interval, …
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in integral2Calc>@(xi,y1i,y2i)integralCalc(@(y)fun(xi*ones(size(y)),y),y1i,y2i,opstruct.integralOptions) (line 17)
innerintegral = @(x)arrayfun(@(xi,y1i,y2i)integralCalc( …
^^^^^^^^^^^^^^^^^
Error in integral2Calc>@(x)arrayfun(@(xi,y1i,y2i)integralCalc(@(y)fun(xi*ones(size(y)),y),y1i,y2i,opstruct.integralOptions),x,ymin(x),ymax(x)) (line 17)
innerintegral = @(x)arrayfun(@(xi,y1i,y2i)integralCalc( …
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in integralCalc>iterateScalarValued (line 334)
fx = FUN(t);
^^^^^^
Error in integralCalc>vadapt (line 148)
[q,errbnd] = iterateScalarValued(u,tinterval,pathlen, …
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in integralCalc (line 113)
[q,errbnd] = vadapt(@minusInfToInfInvTransform,interval, …
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in integral2Calc>integral2i (line 20)
[q,errbnd] = integralCalc(innerintegral,xmin,xmax,opstruct.integralOptions);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in integral2Calc (line 7)
[q,errbnd] = integral2i(fun,xmin,xmax,ymin,ymax,optionstruct);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in integral2 (line 105)
Q = integral2Calc(fun,xmin,xmax,yminfun,ymaxfun,opstruct);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in Structural_Estimation>neg_log_lik_real (line 43)
pdf_value = integral2(f, -Inf, Inf, -Inf, Inf, ‘AbsTol’, 1e-6, ‘RelTol’, 1e-6);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in Structural_Estimation>@(params)neg_log_lik_real(params,data_matrix) (line 58)
neg_log_lik_handle = @(params) neg_log_lik_real(params, data_matrix);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in fminunc (line 233)
f = feval(funfcn{3},x,varargin{:});
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in Structural_Estimation (line 62)
[estimated_params, fval, exitflag, output] = fminunc(neg_log_lik_handle, initial_params, options);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Caused by:
Failure in initial objective function evaluation. FMINUNC cannot continue.
Related documentation optimization, integral2, integral, mle MATLAB Answers — New Questions
How can I save a figure (in jpeg and pdf) from this code?
Display a geographic globe in a figure created using the uifigure function.
uif = uifigure;
g = geoglobe(uif);Display a geographic globe in a figure created using the uifigure function.
uif = uifigure;
g = geoglobe(uif); Display a geographic globe in a figure created using the uifigure function.
uif = uifigure;
g = geoglobe(uif); figure, save, pdf, jpeg, saving, globe, earth, help MATLAB Answers — New Questions
Filter design differences between DSP System and Signal Processing toolboxes (fdesign/design)
The following two lines have different behavior depending on installed toolboxes:
d = fdesign.highpass(‘N,F3db’,3,1,1000);
Hd = design(d);
Normally, I have BOTH DSP System and Signal Processing toolboxes installed. When I run these lines with both toolboxes installed I get the following error:
Error using fdesign.abstracttype/superdesign (line 90)
For symmetric FIR filters, only even orders are allowed.
Now, if I uninstall DSP System toolbox this pair of lines runs as I expect, and makes a 1Hz highpass filter through which I can run my data in lines following the fdesign/design pair of statements. I presume this means that fdesign/design are available in both toolboxes but for some reason only the one in the Signal Processing toolbox works as I expect, meanwhile if I have DSP System installed that version takes precedence and gives me errors.
Is this behavior correct or is it a bug to be reported to Mathworks? I inherited the code from which these lines are excerpted. I also inherited a Matlab license with several toolboxes I know little about (such as DSP System). Though I’ve been working with Matlab on and off for decades I’ve never encountered a case of a function with a "split personality" such as I’m describing with fdesign/design. So from my point of view (limited DSP knowledge) this looks like a bug, but it is possible in my lack of understanding these functions are working correctly with both toolboxes, and therefore I need to learn what I have done (or not done) to cause my errors.The following two lines have different behavior depending on installed toolboxes:
d = fdesign.highpass(‘N,F3db’,3,1,1000);
Hd = design(d);
Normally, I have BOTH DSP System and Signal Processing toolboxes installed. When I run these lines with both toolboxes installed I get the following error:
Error using fdesign.abstracttype/superdesign (line 90)
For symmetric FIR filters, only even orders are allowed.
Now, if I uninstall DSP System toolbox this pair of lines runs as I expect, and makes a 1Hz highpass filter through which I can run my data in lines following the fdesign/design pair of statements. I presume this means that fdesign/design are available in both toolboxes but for some reason only the one in the Signal Processing toolbox works as I expect, meanwhile if I have DSP System installed that version takes precedence and gives me errors.
Is this behavior correct or is it a bug to be reported to Mathworks? I inherited the code from which these lines are excerpted. I also inherited a Matlab license with several toolboxes I know little about (such as DSP System). Though I’ve been working with Matlab on and off for decades I’ve never encountered a case of a function with a "split personality" such as I’m describing with fdesign/design. So from my point of view (limited DSP knowledge) this looks like a bug, but it is possible in my lack of understanding these functions are working correctly with both toolboxes, and therefore I need to learn what I have done (or not done) to cause my errors. The following two lines have different behavior depending on installed toolboxes:
d = fdesign.highpass(‘N,F3db’,3,1,1000);
Hd = design(d);
Normally, I have BOTH DSP System and Signal Processing toolboxes installed. When I run these lines with both toolboxes installed I get the following error:
Error using fdesign.abstracttype/superdesign (line 90)
For symmetric FIR filters, only even orders are allowed.
Now, if I uninstall DSP System toolbox this pair of lines runs as I expect, and makes a 1Hz highpass filter through which I can run my data in lines following the fdesign/design pair of statements. I presume this means that fdesign/design are available in both toolboxes but for some reason only the one in the Signal Processing toolbox works as I expect, meanwhile if I have DSP System installed that version takes precedence and gives me errors.
Is this behavior correct or is it a bug to be reported to Mathworks? I inherited the code from which these lines are excerpted. I also inherited a Matlab license with several toolboxes I know little about (such as DSP System). Though I’ve been working with Matlab on and off for decades I’ve never encountered a case of a function with a "split personality" such as I’m describing with fdesign/design. So from my point of view (limited DSP knowledge) this looks like a bug, but it is possible in my lack of understanding these functions are working correctly with both toolboxes, and therefore I need to learn what I have done (or not done) to cause my errors. fdesign, dsp system toolbox MATLAB Answers — New Questions
stream3 returns error: Sample points must be unique
Hello, I searched the community forum and tried my best to resolve the issue myself, but I could not do it.
Here is my code:
clc; close; clear all;
format compact
%% Cylindrical Coordinates
% Generate cylindrical coordinates
phi = [0 pi/2 pi 3*pi/2];
rho = [0.25 2];
z = [1 2];
% Create a meshgrid for theta, r, and z
[Phi, Rho, Z] = meshgrid(phi, rho, z);
% Convert cylindrical coordinates to Cartesian coordinates
[X, Y, Z] = pol2cart(Phi, Rho, Z);
% Combine X, Y, Z into a single matrix
points = [X(:), Y(:), Z(:)];
% Find unique rows and their indices
[unique_points, ~, ~] = unique(points, ‘rows’);
% Check for duplicates (optional)
num_duplicates = size(points, 1) – size(unique_points, 1);
if num_duplicates > 0
fprintf(‘There are %d duplicate points.n’, num_duplicates);
else
fprintf(‘All points are unique.n’);
end
% Plot the points in 3D space (optional)
figure;
% plot3(X, Y, Z, ‘o’,’DisplayName’,’Sample Points’);
xlabel(‘X’);
ylabel(‘Y’);
zlabel(‘Z’);
title(‘3D Cylindrical Coordinates’);
grid on; axis equal; hold on;
%% Circular magnetic field
% Current in negative z-direction (negative values mean the current
% direction is in positive z-direction)
I = 1;
% Absolute Value of the cylindrical H-field at corresponding positions of
% the radius in phi-direction (all other components are zero)
Hc_phi = 1/(2*pi*Rho);
% Calculate the x-, y- and z-components of the cylindrical field
Hc_x = Hc_phi .* sin(Phi);
Hc_y = -Hc_phi .* cos(Phi);
Hc_z = zeros(size(Z));
% Draw the vector-arrows of the cylindrical field
quiver3(X,Y,Z,Hc_x,Hc_y,Hc_z,’AutoScale’,’off’);
%% Longitudinal magnetic field
Hl = 0.4; % Absolute field strength (+ = neg. z-direction)
Hl_x = zeros(size(X));
Hl_y = zeros(size(Y));
Hl_z = -Hl .* ones(size(Z));
% Draw the vector-arrows of the longitudinal field
quiver3(X,Y,Z,Hl_x,Hl_y,Hl_z,’AutoScale’,’off’);
%% Helical magnetic field (sum of cylindrical and longitudinal field)
H_x = Hc_x + Hl_x;
H_y = Hc_y + Hl_y;
H_z = Hc_z + Hl_z;
% Draw the vector arrows of the helical field
quiver3(X,Y,Z,H_x,H_y,H_z,’AutoScale’,’off’,’LineWidth’,1.5)
% Draw the fieldlines of the helical field
[startX,startY,startZ] = meshgrid([-1 1],[-1 1],1);
% startpoints = [startX(:), startY(:), startZ(:)]; % unique, manually checked
% samplepoints = [X(:), Y(:), Z(:)]; % unique, manually checked
verts = stream3(X,Y,Z,H_x,H_y,H_z,startX,startY,startZ);
lineobj = streamline(verts);
view(3)
Sorry, it might be a bit overwhelming. Ultimately, I just want to get streamlines of H_x, H_y and H_z on the X, Y, Z grid. But I get the following output of the script:
All points are unique.
Error using matlab.internal.math.interp1
Sample points must be unique.
Error in interp1 (line 188)
VqLite = matlab.internal.math.interp1(X,V,method,method,Xqcol);
Error in stream3 (line 66)
syi=interp1(yy(:),1:szu(1),sy(k));
Error in test (line 62)
verts = stream3(X,Y,Z,H_x,H_y,H_z,startX,startY,startZ);
What is the Problem here? Is my check for unique points wrong?
Thank you very much in advance!Hello, I searched the community forum and tried my best to resolve the issue myself, but I could not do it.
Here is my code:
clc; close; clear all;
format compact
%% Cylindrical Coordinates
% Generate cylindrical coordinates
phi = [0 pi/2 pi 3*pi/2];
rho = [0.25 2];
z = [1 2];
% Create a meshgrid for theta, r, and z
[Phi, Rho, Z] = meshgrid(phi, rho, z);
% Convert cylindrical coordinates to Cartesian coordinates
[X, Y, Z] = pol2cart(Phi, Rho, Z);
% Combine X, Y, Z into a single matrix
points = [X(:), Y(:), Z(:)];
% Find unique rows and their indices
[unique_points, ~, ~] = unique(points, ‘rows’);
% Check for duplicates (optional)
num_duplicates = size(points, 1) – size(unique_points, 1);
if num_duplicates > 0
fprintf(‘There are %d duplicate points.n’, num_duplicates);
else
fprintf(‘All points are unique.n’);
end
% Plot the points in 3D space (optional)
figure;
% plot3(X, Y, Z, ‘o’,’DisplayName’,’Sample Points’);
xlabel(‘X’);
ylabel(‘Y’);
zlabel(‘Z’);
title(‘3D Cylindrical Coordinates’);
grid on; axis equal; hold on;
%% Circular magnetic field
% Current in negative z-direction (negative values mean the current
% direction is in positive z-direction)
I = 1;
% Absolute Value of the cylindrical H-field at corresponding positions of
% the radius in phi-direction (all other components are zero)
Hc_phi = 1/(2*pi*Rho);
% Calculate the x-, y- and z-components of the cylindrical field
Hc_x = Hc_phi .* sin(Phi);
Hc_y = -Hc_phi .* cos(Phi);
Hc_z = zeros(size(Z));
% Draw the vector-arrows of the cylindrical field
quiver3(X,Y,Z,Hc_x,Hc_y,Hc_z,’AutoScale’,’off’);
%% Longitudinal magnetic field
Hl = 0.4; % Absolute field strength (+ = neg. z-direction)
Hl_x = zeros(size(X));
Hl_y = zeros(size(Y));
Hl_z = -Hl .* ones(size(Z));
% Draw the vector-arrows of the longitudinal field
quiver3(X,Y,Z,Hl_x,Hl_y,Hl_z,’AutoScale’,’off’);
%% Helical magnetic field (sum of cylindrical and longitudinal field)
H_x = Hc_x + Hl_x;
H_y = Hc_y + Hl_y;
H_z = Hc_z + Hl_z;
% Draw the vector arrows of the helical field
quiver3(X,Y,Z,H_x,H_y,H_z,’AutoScale’,’off’,’LineWidth’,1.5)
% Draw the fieldlines of the helical field
[startX,startY,startZ] = meshgrid([-1 1],[-1 1],1);
% startpoints = [startX(:), startY(:), startZ(:)]; % unique, manually checked
% samplepoints = [X(:), Y(:), Z(:)]; % unique, manually checked
verts = stream3(X,Y,Z,H_x,H_y,H_z,startX,startY,startZ);
lineobj = streamline(verts);
view(3)
Sorry, it might be a bit overwhelming. Ultimately, I just want to get streamlines of H_x, H_y and H_z on the X, Y, Z grid. But I get the following output of the script:
All points are unique.
Error using matlab.internal.math.interp1
Sample points must be unique.
Error in interp1 (line 188)
VqLite = matlab.internal.math.interp1(X,V,method,method,Xqcol);
Error in stream3 (line 66)
syi=interp1(yy(:),1:szu(1),sy(k));
Error in test (line 62)
verts = stream3(X,Y,Z,H_x,H_y,H_z,startX,startY,startZ);
What is the Problem here? Is my check for unique points wrong?
Thank you very much in advance! Hello, I searched the community forum and tried my best to resolve the issue myself, but I could not do it.
Here is my code:
clc; close; clear all;
format compact
%% Cylindrical Coordinates
% Generate cylindrical coordinates
phi = [0 pi/2 pi 3*pi/2];
rho = [0.25 2];
z = [1 2];
% Create a meshgrid for theta, r, and z
[Phi, Rho, Z] = meshgrid(phi, rho, z);
% Convert cylindrical coordinates to Cartesian coordinates
[X, Y, Z] = pol2cart(Phi, Rho, Z);
% Combine X, Y, Z into a single matrix
points = [X(:), Y(:), Z(:)];
% Find unique rows and their indices
[unique_points, ~, ~] = unique(points, ‘rows’);
% Check for duplicates (optional)
num_duplicates = size(points, 1) – size(unique_points, 1);
if num_duplicates > 0
fprintf(‘There are %d duplicate points.n’, num_duplicates);
else
fprintf(‘All points are unique.n’);
end
% Plot the points in 3D space (optional)
figure;
% plot3(X, Y, Z, ‘o’,’DisplayName’,’Sample Points’);
xlabel(‘X’);
ylabel(‘Y’);
zlabel(‘Z’);
title(‘3D Cylindrical Coordinates’);
grid on; axis equal; hold on;
%% Circular magnetic field
% Current in negative z-direction (negative values mean the current
% direction is in positive z-direction)
I = 1;
% Absolute Value of the cylindrical H-field at corresponding positions of
% the radius in phi-direction (all other components are zero)
Hc_phi = 1/(2*pi*Rho);
% Calculate the x-, y- and z-components of the cylindrical field
Hc_x = Hc_phi .* sin(Phi);
Hc_y = -Hc_phi .* cos(Phi);
Hc_z = zeros(size(Z));
% Draw the vector-arrows of the cylindrical field
quiver3(X,Y,Z,Hc_x,Hc_y,Hc_z,’AutoScale’,’off’);
%% Longitudinal magnetic field
Hl = 0.4; % Absolute field strength (+ = neg. z-direction)
Hl_x = zeros(size(X));
Hl_y = zeros(size(Y));
Hl_z = -Hl .* ones(size(Z));
% Draw the vector-arrows of the longitudinal field
quiver3(X,Y,Z,Hl_x,Hl_y,Hl_z,’AutoScale’,’off’);
%% Helical magnetic field (sum of cylindrical and longitudinal field)
H_x = Hc_x + Hl_x;
H_y = Hc_y + Hl_y;
H_z = Hc_z + Hl_z;
% Draw the vector arrows of the helical field
quiver3(X,Y,Z,H_x,H_y,H_z,’AutoScale’,’off’,’LineWidth’,1.5)
% Draw the fieldlines of the helical field
[startX,startY,startZ] = meshgrid([-1 1],[-1 1],1);
% startpoints = [startX(:), startY(:), startZ(:)]; % unique, manually checked
% samplepoints = [X(:), Y(:), Z(:)]; % unique, manually checked
verts = stream3(X,Y,Z,H_x,H_y,H_z,startX,startY,startZ);
lineobj = streamline(verts);
view(3)
Sorry, it might be a bit overwhelming. Ultimately, I just want to get streamlines of H_x, H_y and H_z on the X, Y, Z grid. But I get the following output of the script:
All points are unique.
Error using matlab.internal.math.interp1
Sample points must be unique.
Error in interp1 (line 188)
VqLite = matlab.internal.math.interp1(X,V,method,method,Xqcol);
Error in stream3 (line 66)
syi=interp1(yy(:),1:szu(1),sy(k));
Error in test (line 62)
verts = stream3(X,Y,Z,H_x,H_y,H_z,startX,startY,startZ);
What is the Problem here? Is my check for unique points wrong?
Thank you very much in advance! stream3 MATLAB Answers — New Questions
How to convert a series of x,y,z points to the appropriate format for isosurface?
Hello,
I have a series of points X,Y,Z and I need to plot the isosurface describing these points.
The number of uniques X values is not equal to the unique numbers of the Y values.
Not sure how to produce the X abd Y vexros an the coirresponding Z vector.
Thak youHello,
I have a series of points X,Y,Z and I need to plot the isosurface describing these points.
The number of uniques X values is not equal to the unique numbers of the Y values.
Not sure how to produce the X abd Y vexros an the coirresponding Z vector.
Thak you Hello,
I have a series of points X,Y,Z and I need to plot the isosurface describing these points.
The number of uniques X values is not equal to the unique numbers of the Y values.
Not sure how to produce the X abd Y vexros an the coirresponding Z vector.
Thak you isosurface, plot, colormap MATLAB Answers — New Questions
Truncated VideoReader width value when reading .mov files
I am getting a consistently truncated video pixel width value when reading in my .mov files into my script using VideoReader(). This is a new issue that showed up when i started using a macbook with M3 chip (this was not an issue on my intel chip mac). The video file info description says that the dimensions are 720×480, however the return dimensions from VideoReader() say the dimensions are 640×480. Displaying a video frame confirms that part of my image is cut off on the right side.
Any help or explanation is appreciated, thanks!I am getting a consistently truncated video pixel width value when reading in my .mov files into my script using VideoReader(). This is a new issue that showed up when i started using a macbook with M3 chip (this was not an issue on my intel chip mac). The video file info description says that the dimensions are 720×480, however the return dimensions from VideoReader() say the dimensions are 640×480. Displaying a video frame confirms that part of my image is cut off on the right side.
Any help or explanation is appreciated, thanks! I am getting a consistently truncated video pixel width value when reading in my .mov files into my script using VideoReader(). This is a new issue that showed up when i started using a macbook with M3 chip (this was not an issue on my intel chip mac). The video file info description says that the dimensions are 720×480, however the return dimensions from VideoReader() say the dimensions are 640×480. Displaying a video frame confirms that part of my image is cut off on the right side.
Any help or explanation is appreciated, thanks! video processing MATLAB Answers — New Questions
Is there a meaningful guideline on when to use parentheses vs square brackets vs curly brackets in writing MatLab code?
Is there a meaningful guideline on when to use parentheses vs square brackets vs curly brackets in writing MatLab code? I looked in the FAQ and did not see answers. After completing a handful of MatLab courses I thought I had some understanding, but I also see code that convinces me that I do not know the answer. (Use square brackets for concatination of strings…..but not always? Defining a vector can use parentheses OR square brackets? but not always? Indexing can use parentheses OR square brackets? …but not always? To pass a value to a function use parentheses? Matrix concatenation use square brackets? To construct matrix use square brackets? Plot functions use parentheses?Is there a meaningful guideline on when to use parentheses vs square brackets vs curly brackets in writing MatLab code? I looked in the FAQ and did not see answers. After completing a handful of MatLab courses I thought I had some understanding, but I also see code that convinces me that I do not know the answer. (Use square brackets for concatination of strings…..but not always? Defining a vector can use parentheses OR square brackets? but not always? Indexing can use parentheses OR square brackets? …but not always? To pass a value to a function use parentheses? Matrix concatenation use square brackets? To construct matrix use square brackets? Plot functions use parentheses? Is there a meaningful guideline on when to use parentheses vs square brackets vs curly brackets in writing MatLab code? I looked in the FAQ and did not see answers. After completing a handful of MatLab courses I thought I had some understanding, but I also see code that convinces me that I do not know the answer. (Use square brackets for concatination of strings…..but not always? Defining a vector can use parentheses OR square brackets? but not always? Indexing can use parentheses OR square brackets? …but not always? To pass a value to a function use parentheses? Matrix concatenation use square brackets? To construct matrix use square brackets? Plot functions use parentheses? use parentheses, use square brackets, use curly brackets MATLAB Answers — New Questions