https://in.mathworks.com/matlabcentral/answers/questionsMATLAB Answers — New Questions2020-02-25T00:36:57Ztag:in.mathworks.com,2005:Question/5072692020-02-24T16:16:13Z2020-02-25T00:35:36ZError using @regress fuctionHello, I am trying to create a function as follows with a set of variables that I get from a table named Change1:
X = [Change1.Ones Change1.ReturnsMarket]
func = @regress(Change1.ReturnsCleaned,X);
However, everytime I get the following error message:
Invalid expression. When calling a function or indexing a variable, use parentheses. Otherwise, check for
mismatched delimiters.
Thank you all for your help !Nabil Benhaddahttps://in.mathworks.com/matlabcentral/profile/authors/12030770-nabil-benhaddatag:in.mathworks.com,2005:Question/5073262020-02-24T22:01:15Z2020-02-25T00:25:13ZMultiple errors when using MATLAB function blockI am trying to control a 7 segment display using MATLAB and Simulink with the add on packages that allow them to be used with an Aruduino. My code should be correct but when I try to build and upload I get a tone of errors. I am using 2019b. Please Help!
Gavin Allenhttps://in.mathworks.com/matlabcentral/profile/authors/17376059-gavin-allentag:in.mathworks.com,2005:Question/1605522014-10-29T11:20:47Z2020-02-25T00:24:10ZCorrect simulink transfer function to use with backward shift operator Z^-1Hi
Does anyone know the best transfer funtion to use for the transfer function in the document attached.
a = -0.75
b = 0.2
I've tried using the discrete transfer function but dont get the gain/magnitude at steady state that i would expect. I am rusty with simulink as i used it for my degree but used it with Laplace transforms instead.
Many thanks in advance and kind regards
LiamLiam McNallyhttps://in.mathworks.com/matlabcentral/profile/authors/5029519-liam-mcnallytag:in.mathworks.com,2005:Question/5065452020-02-20T05:52:14Z2020-02-25T00:17:58ZHow to detect rectangle in an image then crop it out? Hi All,
I wish to detect the rectangle as shown below in the image. After that, I want to crop out what's only inside the rectangle part.
Anyone can teach me how?
First, I changed this coloured image into grayscale image then to binary image. Then, I tried using 'regionprops' with 'BoundingBox' to detect the presence of rectangle. However, the cropped image is not exactly the rectangle size.
PS. I do refer from someone else code.
% Find boundary box
props = regionprops(binaryImage, 'BoundingBox');
boundingBox = props.BoundingBox;
width = boundingBox(3);
height = boundingBox(4);
% Crop off the top, shaded portion of column headers,
% which are known to be a fixed 29% of the height of the box.
newHeight = height * (1 - 0.29)
% Make a new bounding box.
xLeft = boundingBox(1);
yTop = boundingBox(2);
boundingBox2 = [xLeft, yTop + 0.29 * height, width, newHeight];
% Crop the image
newGrayScaleImage = imcrop(grayImage, boundingBox2);
subplot(2, 3, 6);
imshow(newGrayScaleImage);
axis('on', 'image');
impixelinfo;
title('New Gray Scale Image', 'FontSize', fontSize);
Result:
WanYuhttps://in.mathworks.com/matlabcentral/profile/authors/17399727-wanyutag:in.mathworks.com,2005:Question/5072142020-02-24T10:15:50Z2020-02-25T00:17:48ZHow can I save different view parameters for a mesh (generated from array)?I have an array (containing values of heights of a surface) from which I am generating a mesh. What I want to do is to generate different camera lines of sight of this mesh, and save them into separate image files.
Currently I generate the mesh, apply a line of sight angle (e.g. view(20,30)) and then use getframe to save the image, but this takes time as I have to display the new view before I can capture it. Moreover, the getframe command is basically taking a screenshot (or so it would seem) so it really isn't the most efficient way to do it (I get different sized images for each view).
I was wondering firstly if this is even possible to do in matlab (perhaps some other package is better), and if it is possible how I can implement this?
Thank you in advance.Ahmhttps://in.mathworks.com/matlabcentral/profile/authors/17620400-ahmtag:in.mathworks.com,2005:Question/5073392020-02-25T00:16:32Z2020-02-25T00:36:57ZHi, I am a highschool student whos brand new to MATLAB and have an equation I would like to plug in and have my data substituted in called the cole-cole equation but I don't have an idea where to start. If anyone could help me thank you!Hi, I am a highschool student whos brand new to MATLAB and have an equation I would like to plug in and have my data substituted in called the cole-cole equation but I don't have an idea where to start. If anyone could help me thank you!Dylan Zelkohttps://in.mathworks.com/matlabcentral/profile/authors/17626860-dylan-zelkotag:in.mathworks.com,2005:Question/5071262020-02-23T19:56:15Z2020-02-25T00:10:57Zkeep getting errors on matlabt = xlsread('trandom','E2:E59');
y = xlsread(rtemp.xlsx','H2:H59');
N=58;
for i=1:N
A=[N sum(sin(t(i)) sum(cos(t(i))
sum(sin(t(i)) sum(sin(t(i))*sin(t(i)) sum(sin(t(i))cos(t(i))
sum(cos(t(i)) sum(sin(t(i))cos(t(i)) sum(cos(t(i))*cos(t(i))];
B=[sum y(i)
sum(y(i)sin(t(i))
sum(y(i)cos(t(i))];
end
X=A\B
idea is to solve ax=b for x, where ive written sum= summation of each i term of t or y
keep getting errors, not confident with matlab
Thanks for any help givenBoss Manhttps://in.mathworks.com/matlabcentral/profile/authors/11512976-boss-mantag:in.mathworks.com,2005:Question/5073032020-02-24T19:18:16Z2020-02-25T00:09:36ZBest Scenario (Optimization)Hello everyone,
I have the following table. In my colums (AA to DD) I have durations (in hrs), and the Name column tells me the location. So for example AA has to spent 148 hrs in 1A to get things done and if AA works alone it'll spend a total of 74 days (assuming it works 15 hrs/day and 7 days), the same thing for BB, etc.
Now I want to choose AA but I want to get things done in 6 weeks instead of 10.5, so I want the help of BB or CC or DD.
Visually speaking, I thought AA could spend time in specific locations spending a time of 5.9 weeks and BB in the rest spend 6.4 (a bit higher than 6 weeks) so maybe a location can be shared.
I want to try to see what scenario matlab would give me, but I don't know how to even start it.
I thought maybe a while loop could be the answer but the more I try the more I get lost. I know I want to use AA but I don't know which location would be best for it (time wise) and in which combination BB/CC/DD.
Any guidance would be appreciated. If anything is unclear please let me know
Thank you
John Doehttps://in.mathworks.com/matlabcentral/profile/authors/10983311-john-doetag:in.mathworks.com,2005:Question/5073382020-02-25T00:06:52Z2020-02-25T00:06:52Zhow to find duration of peak; starting and ending points I've used findpeaks to isolate the largest peak in my signal. I wanted some help in finding the duration of the peak aka the starting and ending points of this peak, so that I could calculate area under curve? Right now Im having to visually inspect and pick arbitrary points to define this start and end points.
Raheema Al Karim Damanihttps://in.mathworks.com/matlabcentral/profile/authors/15751635-raheema-al-karim-damanitag:in.mathworks.com,2005:Question/5071932020-02-24T08:16:36Z2020-02-25T00:01:03Zcropping 2 images togetherMy goal is to cut out similar regions from 2 images.
I’m using the example method shown in ‘normxcorr2()’ to find similar regions from two images, and am using ‘imcrop()’ to cut those areas.
What I want to ask is if there is a way to cut both images when the overlapping area doesn’t completely fit inside the larger image.
For example, I have 2 images ‘A’ and ‘B’ sized 1865*1200 and 904*670 respectively. And from the normxcorr2 function I get [xpeak=799, ypeak=846] and from that [xoffset=129, yoffset=-58]. This makes area [130 -57 670 904] to be the highest similarity, which is not inside ‘A’.
Is there a way to cut out the overlapping area from both ‘A’ and ‘B’ without the process of manually calculating the coordinates where they overlap?
Thank you in advance for your help.Hoyong Yiehttps://in.mathworks.com/matlabcentral/profile/authors/17435168-hoyong-yietag:in.mathworks.com,2005:Question/5072822020-02-24T17:03:18Z2020-02-24T23:54:36ZBehaviour of backslash operator for non-square matrices least-squares fittingI am currently trying to reproduce a set of results from a pre-existing project and can't get to the bottom of the following difference.
Phi = design matrix of input data size(29507x97)
Ref = reference values to fit to, six data sets, size(29507x6)
Phi = rand(29507,97);
Ref = rand(29507,6);
c1 = Phi\Ref;
for ii = 1:6
c2(:,ii) = Phi\Ref(:,ii);
end
all(all(c1==c2))
I would have expected c1 to give identical results to c2. I can't find detailed information on what the "\" algorithm is doing differently between these case.
Any help appreciated!
Matt O'Donnellhttps://in.mathworks.com/matlabcentral/profile/authors/7775423-matt-o-donnelltag:in.mathworks.com,2005:Question/4827322019-09-29T18:59:43Z2020-02-24T23:52:05ZIndex in position 2 is invalid. Array indices must be positive integers or logical values. I=zeros(1,1);
f=zeros(1,1);
n=0;
m=0;
for ky=-6:0.1:6
for kx=-6:0.1:6
f(10*ky+61,10*kx+61)=exp(i*10^(-16)*(2.16*(n+m)*kx+1.245*(n-m)*ky))
I(10*ky+61,10*kx+61)=f(10*ky+61,10*kx+61).^2
end
end
contourf(-6:0.1:6,-6:0.1:6,I,'LineStyle','none');
The error says" Error in hw0928 (line 13) f(10*ky+61,10*kx+61)=exp(i*10^(-16)*(2.16*(n+m)*kx+1.245*(n-m)*ky))" What is worng?
Zhiying Wanghttps://in.mathworks.com/matlabcentral/profile/authors/16207920-zhiying-wangtag:in.mathworks.com,2005:Question/5067132020-02-21T01:05:47Z2020-02-24T23:48:21ZHow to show only elliptic region in color? Dear experts,
How can I get a plot like below in which no color will be shown outside of the ellipse?
If I use pcolor and I get a surface like below where outside of larger ellipse is filled with blue color that I don’t want.
A part of my code is given here.
pcolor(x1, y1, SS);
colormap jet
colorbar
hold on
quiver(x, y, sx, sy,'k'); % plot vector
hold on
x2 = x(TT > 0);
y2 = y(TT > 0);
ff2 = boundary(x2, y2);
plot(x2(ff2), y2(ff2),'r'); % plot outer boundary line
hold on
x3 = x(TT>0 & SS == 0);
y3 = y(TT>0 & SS == 0);
ff3 = boundary(x3, y3);
hold on
plot(x3(ff3), y3(ff3), 'r') % plot inner boundary line
Thanks in advanced.
Abdul Mannanhttps://in.mathworks.com/matlabcentral/profile/authors/15162704-abdul-mannantag:in.mathworks.com,2005:Question/5073312020-02-24T22:33:52Z2020-02-24T23:46:22ZFinding Distance Between Points and a CurveHi All,
I have attached two plots I would like to analyze. In both of these plots, I would like to find the vertical distance between most of the points (excluding the points that are left of the curves) and the curve. As in, for each point, I would like to imagine a vertical line extending from the point to the curve, and then find the length of this line. Ultimately, I would like to have produced two column vectors, a and b, for each of the two plots, and then create one final column vector, a^2+b^2.
Does anybody have any insight as to how to do this?
Please let me know if I could provide more helpful information as well.
Thanks
Jonathan Pinkohttps://in.mathworks.com/matlabcentral/profile/authors/17139283-jonathan-pinkotag:in.mathworks.com,2005:Question/5073372020-02-24T23:45:28Z2020-02-24T23:45:28ZRepeated measures ANOVA output not consistent with SPSS???Hi I am running a two way ANOVA in which both IVs (Filter type and Ground Clutter) are within-subject design
% I used Matlab with the following code to run repeated measures ANOVA
Operator = [1 2 3 4]';
D1 = [90 96 100 92]';
D2 = [86 84 92 81]';
D3 = [102 106 105 96]';
D4 = [87 90 97 80]';
D5 = [114 112 108 98]';
D6 = [93 91 95 83]';
tbl = table(Operator,D1,D2,D3,D4,D5,D6)
GroundClutter = {'L';'L';'M';'M';'H';'H'};
Filter = {'1';'2';'1';'2';'1';'2'};
WithinVariables = table(GroundClutter,Filter);
rm = fitrm(tbl,'D1-D6~1','WithinDesign', WithinVariables);
ranovatbl = ranova(rm,'WithinModel','GroundClutter*Filter')
The output is as follows:
Each variable has their own error term rather than classic ANOVA model which only has one term and the output from SPSS is as follows
You can see that the SS terms are same except the error term from SPSS output is the sum of the respective error terms (4,6,8 in the second figure). I am not sure what the intercept (1 in the second figure) mean, which is the between subject variable while I have include that in the model in order to run it... Can I remove that?
How to produce results using Matlab similar to the SPSS output?Feng Zhouhttps://in.mathworks.com/matlabcentral/profile/authors/11008415-feng-zhoutag:in.mathworks.com,2005:Question/5073222020-02-24T21:28:20Z2020-02-24T23:38:37ZError using splitapply(Regress)Hello, I have a given set of values that I was able to divide as groups from a table named 'Change1', however I get the following error message when trying to use the splitapply function:
Error using splitapply (line 61)
Group numbers must be a vector of positive integers, and cannot be a sparse vector.
Error in Untitled (line 8)
Regress = splitapply(func,X,Q);
I named the collumn containing the number that decides of the grouping as 'Numero', the column containing the ones to use for calculating the regressions intercepts as 'Ones'
The code is as follows:
Change1.Groups = findgroups(Change1.Numero);
X = [Change1.Groups Change1.Ones Change1.ReturnsMarket];
Q = Change1.ReturnsCleaned;
func = @(Q)regress(Q,X);
Regress = splitapply(func,X,Q);Nabil Benhaddahttps://in.mathworks.com/matlabcentral/profile/authors/12030770-nabil-benhaddatag:in.mathworks.com,2005:Question/5073362020-02-24T23:28:48Z2020-02-24T23:31:16ZHow do I minimize this codeHow do I minimize this,
A=input('Enter Matrix A: ')
B=input('Enter Matrix B: ')
C=input('Enter Matrix C: ')
n=length(A);
Con=B;
Obs=C;
for x = 1: n-1
Con =[Con, A^(x)*B];
Obs =[Obs, C*A^(x)];
end
[a,b]=size(Con);
[c,d]=size(Obs);
if a==b
if det(Con)~=0
input('The systeme is controlable')
else
input('The systeme is not controlable')
end
elseif a~=b
if rank(Con)==n
input('The systeme is controlable')
else
input('The systeme is not controlable')
end
end
if c==d
if det(Obs)~=0
input('The systeme is observable')
else
input('The systeme is not observable')
end
elseif c~=d
if rank(Obs)==n
input('The systeme is observable')
else
input('The systeme is not observable')
end
endDavid Hastanahttps://in.mathworks.com/matlabcentral/profile/authors/17626654-david-hastanatag:in.mathworks.com,2005:Question/5072452020-02-24T13:57:11Z2020-02-24T23:27:21ZHow to solve a second order differential equations with matrices by using "ODE45"?Hi,
I am trying to solve the following 2nd order differential equation...[M]x''+[C]x'+[K]x=fsin(wt) where M,C and K are 3x3 matrices. I am using ODE45 to solve and ideally produce x on y-axis against time on x-axis. I am getting some errors which I believe is due to passing matrices through the code with different dimensions but I am unsure how to reshape them without losing my desired correct result etc.
Any help is much appreciated!
function springmassdamper
tstart = 0;
tend = 60;
n = 10;
tspan = linspace(tstart,tend,n);
xinit = [0;0];
[t,x] = ode45(@integratingfunction, tspan, xinit)
y = x(:,1);
ydot = x(:,2);
plot(tspan,x(:,1))
xlabel('Time')
ylabel('Displacement')
function dxdt = integratingfunction(t,x)
m=[1 0 0;0 1 0;0 0 1];
c=[0.002 -0.001 0;-0.002 0.002 -0.001;0 -0.001 0.001];
k=[2 -1 0;-1 2 -1;0 -1 1];
w=2*pi*50;
f=100;
F=f*sin(w*t);
y=x(1)
ydot=x(2)
dxdt = zeros(size(x));
dxdt(1) = ydot;
dxdt(2) = (1/m)*(F-c*ydot-k*y);
Georgehttps://in.mathworks.com/matlabcentral/profile/authors/11243812-georgetag:in.mathworks.com,2005:Question/5073352020-02-24T23:26:53Z2020-02-24T23:26:53Zlsqcurvefit giving better results for reduced modelI am trying to fit 9 coefficients to a model (piecewise_STS). When I run the code below with c(3) in place of the 0, it fits the 9 coefficents. With the 0, it calculates 8 coefficients and leaves c(3) = 0 (as I would expect). When I calculate the statistic, the reduced model (8 coefficients) is worse than the full model. An additional coefficient should at worst keep the statistic the same. The exit flag is the same for both models, step size tolerance. I appreciate any help!
[c, resnorm, residual, exitflag, output, lambda, J] = lsqcurvefit(...
@(c,x) piecewiseline_STS(P_std, Tc_std, Ts, dT, ...
15, 45, 45, 45, P_lim, STS, ...
c(1), c(2), 0, c(4), c(5), c(6), c(7), c(8), c(9)), ...
[0, 0, 0, 0, 0, 0, 0, 0, 0], ...
(1:length(P))', ...
[P_std; Tc_std]);
Laura Hemmenhttps://in.mathworks.com/matlabcentral/profile/authors/6710682-laura-hemmentag:in.mathworks.com,2005:Question/5073342020-02-24T23:26:38Z2020-02-24T23:26:38ZReaction Diffusion - diffusion in the gridHello,
I have a problem, which i unfortunately have very little idea how to solve.
I want to write a script that describes the evolution of the state variables u and v for each point over an integration grid.
I attached a image of the equations I would like to use. The yellow marked variables are all constant and the blue underlined ones are the diffusive terms.
What I've found so far is this question where they basically solved one part of my problem. They calculeted the solution for the equations without diffusion.
https://de.mathworks.com/matlabcentral/answers/163448-need-some-help-four-coupled-odes-with-ode45
Now i want to extend the code so that it calculates this shift in concentration for ervery cells in a grid (or rather a few cells that surround the cell, that did the shift).
If you have any ideas or thoughts I would be very happy if you could share them with me.
Thanks a lot
Antonio
Antonio Sarusichttps://in.mathworks.com/matlabcentral/profile/authors/11445622-antonio-sarusictag:in.mathworks.com,2005:Question/5073172020-02-24T20:55:33Z2020-02-24T23:20:31ZGetting array out of for loopHello,
I am trying to run a for loop for fixed amount of iteration for variable n and wanna get output variables in one array so that i can have a graph.
but every time I am getting updated value out of loop and all previous values are gone.
Please help me find code that can save array instead of last partivular updated value. My code is as follows;
clc
clear
%% pre-defined variables and equations
p_in = 100;
p_out = 30000;
cr = p_out/p_in;
n = 1;
cr_stage = (p_out/p_in)^(1/n);
%% alghorithm
while cr_stage > 3.99 % cr_stage variable should not exceed 4, otherwise increment in variable n
n(n) = n+1;
cr_stage(n) = (p_out/p_in).^(1./n);
if cr_stage(n) < 3.99 % when its below 4, loop breaks itself.
break
end
end
n_1 = 1;
n = [n_1, n];
cr_stage = cr_stage(end);
stages = numel(n);
for i = n(1):n(end) % for loop for iteration of n times
p_out = p_in * cr_stage % want this variable output in array to have graph
p_in = p_out; % updated value of variable above given.
end
Swapnil Rathvahttps://in.mathworks.com/matlabcentral/profile/authors/12138055-swapnil-rathvatag:in.mathworks.com,2005:Question/5065392020-02-20T05:17:35Z2020-02-24T23:19:47ZI called matlab function in C++ and got LNK2001 error.Hello
C:\Program Files\MATLAB\MATLAB Runtime\v97\extern\lib\win64\mingw64
C:\Program Files\MATLAB\MATLAB Runtime\v97\extern\lib\win64\microsoft
C:\Program Files\MATLAB\MATLAB Runtime\v97\extern\include
C:\Program Files\MATLAB\MATLAB Runtime\v97\bin\win64
C:\Program Files\MATLAB\MATLAB Runtime\v97\lib\win64
C:\Program Files\MATLAB\MATLAB Runtime\v97\runtime\win64
I have already added the above paths to the project.
mclbase.lib, mclcommain.lib, mclmcr.lib, mclmcrrt.lib and mclxlmain.lib were also added.
This causes a LNK2001 unresolved external symbol error in the GT_model function.
The other GT_modelInitialize and mclInitializeApplication functions seem to work well
it seems that lib or dll is added well
GT_model(1, y_pwrOut, inputIn) is not work
i got LNK2001 unrresolved error
I don't know what's wrong.
Thank you for any advice.
Main.cpp
------------------------------------------------------------------------------------
#include <iostream>
#include "GT_model.h"
void GT_modelSample()
{
mxDouble inputInData[] = { -20.0, 101.325, 0.6, 321.3713, -20.0, 100.8011, 281.3149, 873.2329, 2.5707, 200.0, 49492.4247435387, 357.7379, 121.1334, 357.7379, 102.0625, 0.0, 3600.0 };
mwArray inputIn(1, 17, mxDOUBLE_CLASS);
inputIn.SetData(inputInData, 17);
std::cout << "4\n";
mwArray y_pwrOut;
mxArray *plhs;
mxDouble *prhs;
try
{
GT_model(1, y_pwrOut, inputIn);
std::cout << y_pwrOut << std::endl;
std::cout << "5\n";
}
catch (const mwException & e)
{
std::cerr << e.what() << std::endl;
}
catch (...)
{
std::cerr << "Unexpected error thrown" << std::endl;
}
}
int run_main(int argc, const char** argv)
{
std::cout << "2\n";
if (!GT_modelInitialize())
{
std::cerr << "Could not initialize the library properly" << std::endl;
return -2;
}
else
{
std::cout << "3\n";
GT_modelSample();
std::cout << "6\n";
// Call the application and library termination routine
GT_modelTerminate();
std::cout << "7\n";
}
// Note that you should call mclTerminateApplication at the end of
// your application to shut down all MATLAB Runtime instances.
mclTerminateApplication();
std::cout << "8\n";
return 0;
}
// The main routine. On macOS, the main thread runs the system code, and
// user code must be processed by a secondary thread. On other platforms,
// the main thread runs both the system code and the user code.
int main(int argc, const char** argv)
{
/* Call the mclInitializeApplication routine. Make sure that the application
* was initialized properly by checking the return status. This initialization
* has to be done before calling any MATLAB APIs or MATLAB Compiler SDK
* generated shared library functions.
*/
if (!mclmcrInitialize()) {
std::cerr << "Could not initialize the application." << std::endl;
return -1;
}
if (!mclInitializeApplication(nullptr, 0))
{
std::cerr << "Could not initialize the application." << std::endl;
return -1;
}
std::cout << "1\n";
return mclRunMain(static_cast<mclMainFcnType>(run_main), argc, argv);
}
---------------------------------------------------------------------------------
GT_model.h
---------------------------------------------------------------------------------
//
// MATLAB Compiler: 7.1 (R2019b)
// Date: Wed Feb 5 15:51:57 2020
// Arguments:
// "-B""macro_default""-W""cpplib:GT_model,all,version=1.0""-T""link:lib""-d""C:
// \Users\sergey.mishchenko\Desktop\dll
// file\GT_model\for_testing""-v""C:\Users\sergey.mishchenko\Desktop\dll
// file\GT_model.m"
//
#ifndef GT_model_h
#define GT_model_h 1
#if defined(__cplusplus) && !defined(mclmcrrt_h) && defined(__linux__)
# pragma implementation "mclmcrrt.h"
#endif
#include "mclmcrrt.h"
#include "mclcppclass.h"
#ifdef __cplusplus
extern "C" { // sbcheck:ok:extern_c
#endif
/* This symbol is defined in shared libraries. Define it here
* (to nothing) in case this isn't a shared library.
*/
#ifndef LIB_GT_model_C_API
#define LIB_GT_model_C_API /* No special import/export declaration */
#endif
/* GENERAL LIBRARY FUNCTIONS -- START */
extern LIB_GT_model_C_API
bool MW_CALL_CONV GT_modelInitializeWithHandlers(
mclOutputHandlerFcn error_handler,
mclOutputHandlerFcn print_handler);
extern LIB_GT_model_C_API
bool MW_CALL_CONV GT_modelInitialize(void);
extern LIB_GT_model_C_API
void MW_CALL_CONV GT_modelTerminate(void);
extern LIB_GT_model_C_API
void MW_CALL_CONV GT_modelPrintStackTrace(void);
/* GENERAL LIBRARY FUNCTIONS -- END */
/* C INTERFACE -- MLX WRAPPERS FOR USER-DEFINED MATLAB FUNCTIONS -- START */
extern LIB_GT_model_C_API
bool MW_CALL_CONV mlxGT_model(int nlhs, mxArray *plhs[], int nrhs, mxArray *prhs[]);
/* C INTERFACE -- MLX WRAPPERS FOR USER-DEFINED MATLAB FUNCTIONS -- END */
#ifdef __cplusplus
}
#endif
/* C++ INTERFACE -- WRAPPERS FOR USER-DEFINED MATLAB FUNCTIONS -- START */
#ifdef __cplusplus
/* On Windows, use __declspec to control the exported API */
#if defined(_MSC_VER) || defined(__MINGW64__)
#ifdef EXPORTING_GT_model
#define PUBLIC_GT_model_CPP_API __declspec(dllexport)
#else
#define PUBLIC_GT_model_CPP_API __declspec(dllimport)
#endif
#define LIB_GT_model_CPP_API PUBLIC_GT_model_CPP_API
#else
#if !defined(LIB_GT_model_CPP_API)
#if defined(LIB_GT_model_C_API)
#define LIB_GT_model_CPP_API LIB_GT_model_C_API
#else
#define LIB_GT_model_CPP_API /* empty! */
#endif
#endif
#endif
extern LIB_GT_model_CPP_API void MW_CALL_CONV GT_model(int nargout, mwArray& y_pwr, const mwArray& input);
/* C++ INTERFACE -- WRAPPERS FOR USER-DEFINED MATLAB FUNCTIONS -- END */
#endif
#endif
---------------------------------------------------------------------------------HYUK MYEONG KWONhttps://in.mathworks.com/matlabcentral/profile/authors/17587539-hyuk-myeong-kwontag:in.mathworks.com,2005:Question/5071702020-02-24T04:13:09Z2020-02-24T23:17:48ZHiding Plot Elements makes those elements appearing in the legend and the legend itself a much lighter shade than it should be. How to fix this?I am in the process of redoing a figure for a publication that needs to be changed up a bit based on reviewer comments. I have to create a plot legend that covers four different subplots and needs to include elements not included in all four subplots that all have two y-axes. To create the legend, I created an extra row of subplots and merged them to make a dummy subplot. I plotted generic versions of all the plot elements that need to be included in the legend, created the legend, and then hid the plot elements and the subplot itself so that the only thing still visible is the legend which is then dragged into the desired position. All went to plan except for the fact that the the symbols/lines/text in the legend appear to be several shades lighter than they should be. Briefly troubleshooting, I noticed hiding everything is what results in the lighter shades. The first version of the code I wrote to create the figure involved creating two different figures instead of the "two different subplots" and then I just cut and paste the legend into the figure separately outside of MATLAB. It would ideal just to get the plot and legend generated properly by the same code. Code below and figure attached. The code is very long, but the last 21 lines of code are of most interest for this question. Thank you in advance for any and all help.
set(0,'defaultfigurecolor','w');
figure(1)
colormap jet
h1 = subplot(5,5,[1,2,6,7]);
yyaxis left
area(hour1,sal1,'FaceColor',[0.8300 0.8300 0.8300],'EdgeColor',[0.8300 0.8300 0.8300],'LineStyle','-');
ylim([5.6 26.4]);
set(gca,'FontSize',10);
set(gca,'ycolor','k');
set(gca,'ytick',[8 12 16 20 24]);
ytix = get(gca,'ytick');
ytixlbl = regexp(sprintf('%.0f\n',ytix), '\n', 'split');
set(gca,'yticklabel',ytixlbl(1:end-1));
ylabel('Salinity','FontSize',10,'FontWeight','bold');
text(7.0,26.6,'a','FontSize',18,'FontWeight','bold');
str1 = {'01 June 2016'};
text(14.8,25,str1,'FontSize',10,'FontWeight','bold');
yyaxis right
scatter(hour1,ph1,50,'o','filled','MarkerFaceColor',[0 0 0.8]);
hold on
plot(hour1,ph1,'Color',[0 0 0.8],'LineWidth',1,'LineStyle','-');
hold off
ylim([-10.8 82.8]);
set(gca,'FontSize',10);
set(gca,'ycolor','k');
set(gca,'ytick',[0 18 36 54 72]);
ytix = get(gca,'ytick');
ytixlbl = regexp(sprintf('%.0f\n',ytix), '\n', 'split');
set(gca,'yticklabel',ytixlbl(1:end-1));
ylabel('[H^{+}_{T}] (nmol kg^{-1})','FontSize',10,'FontWeight','bold');
xlim([8.5 19.5]);
set(gca,'xtick',[9,11,13,15,17,19]);
xlabel('Hour','FontSize',10,'FontWeight','bold');
set(gca,'FontSize',10);
box on
h2 = subplot(5,5,[4,5,9,10]);
yyaxis left
area(hour1,sal1,'FaceColor',[0.8300 0.8300 0.8300],'EdgeColor',[0.8300 0.8300 0.8300],'LineStyle','-');
ylim([5.6 26.4]);
set(gca,'FontSize',10);
set(gca,'ycolor','k');
set(gca,'ytick',[8 12 16 20 24]);
ytix = get(gca,'ytick');
ytixlbl = regexp(sprintf('%.0f\n',ytix), '\n', 'split');
set(gca,'yticklabel',ytixlbl(1:end-1));
ylabel('Salinity','FontSize',10,'FontWeight','bold');
text(7.0,26.6,'b','FontSize',18,'FontWeight','bold');
str1 = {'01 June 2016'};
text(14.8,25,str1,'FontSize',10,'FontWeight','bold');
yyaxis right
scatter(hour1,dic1,75,'s','filled','MarkerFaceColor',[0.5500 0.7100 0.0000]);
hold on
scatter(hour1,ta1,60,'>','filled','MarkerFaceColor',[0.9100 0.4100 0.1700]);
hold on
plot(hour1,dic1,'Color',[0.5500 0.7100 0.0000],'LineWidth',1,'LineStyle','-');
hold on
plot(hour1,ta1,'Color',[0.9100 0.4100 0.1700],'LineWidth',1,'LineStyle','-');
hold off
ylim([1440 1960]);
set(gca,'FontSize',10);
set(gca,'ycolor','k');
set(gca,'ytick',[1500 1600 1700 1800 1900]);
ytix = get(gca,'ytick');
ytixlbl = regexp(sprintf('%.0f\n',ytix), '\n', 'split');
set(gca,'yticklabel',ytixlbl(1:end-1));
ylabel('DIC or TA (\mumol kg^{-1})','FontSize',10,'FontWeight','bold');
xlim([8.5 19.5]);
set(gca,'xtick',[9,11,13,15,17,19]);
xlabel('Hour','FontSize',10,'FontWeight','bold');
set(gca,'FontSize',10);
box on
h3 = subplot(5,5,[11,12,16,17]);
yyaxis left
area(hour2,sal2,'FaceColor',[0.8300 0.8300 0.8300],'EdgeColor',[0.8300 0.8300 0.8300],'LineStyle','-');
ylim([18.8 29.2]);
set(gca,'FontSize',10);
set(gca,'ycolor','k');
set(gca,'ytick',[20 22 24 26 28]);
ytix = get(gca,'ytick');
ytixlbl = regexp(sprintf('%.0f\n',ytix), '\n', 'split');
set(gca,'yticklabel',ytixlbl(1:end-1));
ylabel('Salinity','FontSize',10,'FontWeight','bold');
text(6.05,29.3,'c','FontSize',18,'FontWeight','bold');
str1 = {'02 August 2016'};
text(14.93,28.5,str1,'FontSize',10,'FontWeight','bold');
yyaxis right
scatter(hour2,ph2,50,'o','filled','MarkerFaceColor',[0 0 0.8]);
hold on
plot(hour2,ph2,'Color',[0 0 0.8],'LineWidth',1,'LineStyle','-');
hold off
ylim([-2 102]);
set(gca,'FontSize',10);
set(gca,'ycolor','k');
set(gca,'ytick',[10 30 50 70 90]);
ytix = get(gca,'ytick');
ytixlbl = regexp(sprintf('%.0f\n',ytix), '\n', 'split');
set(gca,'yticklabel',ytixlbl(1:end-1));
ylabel('[H^{+}_{T}] (nmol kg^{-1})','FontSize',10,'FontWeight','bold');
xlim([7.75 20]);
set(gca,'xtick',[8 10 12 14 16 18 20]);
xlabel('Hour','FontSize',10,'FontWeight','bold');
set(gca,'FontSize',10);
box on
p3 = get(h3,'Position');
p3(2) = p3(2)-0.015;
set(h3,'pos',p3);
h4 = subplot(5,5,[14,15,19,20]);
yyaxis left
area(hour2,sal2,'FaceColor',[0.8300 0.8300 0.8300],'EdgeColor',[0.8300 0.8300 0.8300],'LineStyle','-');
ylim([18.8 29.2]);
set(gca,'FontSize',10);
set(gca,'ycolor','k');
set(gca,'ytick',[20 22 24 26 28]);
ytix = get(gca,'ytick');
ytixlbl = regexp(sprintf('%.0f\n',ytix), '\n', 'split');
set(gca,'yticklabel',ytixlbl(1:end-1));
ylabel('Salinity','FontSize',10,'FontWeight','bold');
text(6.05,29.3,'d','FontSize',18,'FontWeight','bold');
str1 = {'02 August 2016'};
text(14.93,28.5,str1,'FontSize',10,'FontWeight','bold');
yyaxis right
scatter(hour2,dic2,75,'s','filled','MarkerFaceColor',[0.5500 0.7100 0.0000]);
hold on
scatter(hour2,ta2,60,'>','filled','MarkerFaceColor',[0.9100 0.4100 0.1700]);
hold on
plot(hour2,dic2,'Color',[0.5500 0.7100 0.0000],'LineWidth',1,'LineStyle','-');
hold on
plot(hour2,ta2,'Color',[0.9100 0.4100 0.1700],'LineWidth',1,'LineStyle','-');
hold off
ylim([1740 2260]);
set(gca,'FontSize',10);
set(gca,'ycolor','k');
set(gca,'ytick',[1800 1900 2000 2100 2200]);
ytix = get(gca,'ytick');
ytixlbl = regexp(sprintf('%.0f\n',ytix), '\n', 'split');
set(gca,'yticklabel',ytixlbl(1:end-1));
ylabel('DIC or TA (\mumol kg^{-1})','FontSize',10,'FontWeight','bold');
xlim([7.75 20]);
set(gca,'xtick',[8 10 12 14 16 18 20]);
xlabel('Hour','FontSize',10,'FontWeight','bold');
set(gca,'FontSize',10);
box on
p4 = get(h4,'Position');
p4(2) = p4(2)-0.015;
set(h4,'pos',p4);
h5 = subplot(5,5,[21,22,23,24,25]);
set(0,'defaultfigurecolor','w');
colormap jet
element1 = area(hour1,sal1,'FaceColor',[0.8300 0.8300 0.8300],'EdgeColor',[0.8300 0.8300 0.8300],'LineStyle','-');
hold on
element2 = plot(hour1,ph1,'-o','MarkerEdgeColor',[0 0 0.8],'LineWidth',1,'MarkerFaceColor',[0 0 0.8],'MarkerSize',7,'Color',[0 0 0.8]);
hold on
element3 = plot(hour1,dic1,'-s','MarkerEdgeColor',[0.5500 0.7100 0.000],'LineWidth',1,'MarkerFaceColor',[0.5500 0.7100 0.000],'MarkerSize',10,'Color',[0.5500 0.7100 0.0000]);
hold on
element4 = plot(hour1,ta1,'->','MarkerEdgeColor',[0.9100 0.4100 0.1700],'LineWidth',1,'MarkerFaceColor',[0.9100 0.4100 0.1700],'MarkerSize',7,'Color',[0.9100 0.4100 0.1700]);
hold off
plotleg = legend('Salinity','[H^{+}_{T}]','DIC','TA','Location','bestoutside','Orientation','vertical');
legend('boxon');
set(plotleg,'FontSize',13);
box off
axis off
set(element1,'Visible','off');
set(element2,'Visible','off');
set(element3,'Visible','off');
set(element4,'Visible','off');
set(h5,'Visible','off');
S_Ghttps://in.mathworks.com/matlabcentral/profile/authors/8525791-s_gtag:in.mathworks.com,2005:Question/5073282020-02-24T22:04:30Z2020-02-24T23:14:39Zsaving data during iterationsI am working on some iterative calculations and I need to be able to save the results of the iteration at various times during the calculation.
I know that I can plot the results of each step with "hold on" and the plot command. What I cannot figure out is how to write the results of each iteration either to the workspace as a new variable or to a file so that I can load it into something else later,
Here is what I have so far
x = [1 2 3 4 5]
y= [1.5, 2.5, 3.5, 4.5, 5.5]
for k=1:10
buff1 = y
for x=1:5
y(x)=buff1(i)+y(i)
end
hold on
plot(x, y)
end
What I want to do is to have a listing of y for each of the 10 iterations.
Thanks
Cliff
Cliff Shawhttps://in.mathworks.com/matlabcentral/profile/authors/3586030-cliff-shawtag:in.mathworks.com,2005:Question/5073052020-02-24T19:37:49Z2020-02-24T23:08:52ZSplitting a vector into separate vectors using thresholdsHello,
So, I have data from a shoe insole that collects ground reaction force during running. Basically, i get one continous vector that is composed of multiple steps. I am trying to separate this vector into multiple separate vectors based off of when foot contact occurs (when force >= 20) and when toe-off occurs (when force <= 10). For the sake of understanding, if I have a vector x: x = [0 10 20 30 40 50 40 30 20 10 0 10 20 30 40 50 40 30 20 10 0], and I want to create a loop that says "when force is greater than or equal to 20, create a vector and end that vector when force is less than or equal to 10. Then when force is greater than or equal to 20 again, create a new vector and end that vector when the froe is less than or equal to 10. And so on and so forth..".
So far, I have this:
x = [0 10 20 30 40 50 40 30 20 10 0 10 20 30 40 50 40 30 20 10 0]
for i = 1:length(x)
y = find(x>=20)
stance = x(y)
end
But I am having trouble trying to figure out how to separate this into multiple vectors according to the above criteria. Can anyone help out with this?Joseph Gonzaleshttps://in.mathworks.com/matlabcentral/profile/authors/16697852-joseph-gonzalestag:in.mathworks.com,2005:Question/5069712020-02-22T15:09:41Z2020-02-24T23:06:30ZHow to convert .mat file to png format?How to convert .mat file to png format?Rida Memonhttps://in.mathworks.com/matlabcentral/profile/authors/17346057-rida-memontag:in.mathworks.com,2005:Question/5068192020-02-21T14:21:47Z2020-02-24T23:03:35ZConstrained Global Optimization Problem with MultiStart, GA and HybridFunction using Parallel Processing whithout StepHello,
I am interested in using a genetic algorithm approach to fitting measurement data to a function of 3 variables with 4 unknown coefficients.
I am not concerned with the computational time required for the genetic approach, as, for now, I am just trying to develop a methodology for fitting complex, non-linear/non-smooth, functions using the various features available in Matlab's Global Optimization toolbox. The complexity and non-linearity of my function (presented below) will greatly increase in the near future.
The function which I am trying to fit my data to is defined as following:
VALUE=a1*x+a2*ln(y)+a3*abs(z)+a4
With: a1,a2,a3,a4 being the regression model's unknown coefficients
The following optimization constraints need to be imposed on the coefficients of the function:
a3<0; a4>0; a1*a2<0;
The data to which I am trying to fit my function to is presented in the attached SampleData.csv file. The file contains column labels which define the measured value and x,y,z parameters.
My initial guesses for the values of a1,a2,a3,a4 are defined as a row vector: [0,0,0,0].
I would like to learn how to set this problem up using MultiStart and parallel processing. I would like to use parallel processing for the MultiStart process, as well as to include a Hybrid Function, if such an operation is possible.
The work flow which I would like to achieve should be similar to:
1. Define Function (referring to x,y,z data contained in columns of SampleData.csv file) :
function [ Value ] = FittingFunction(x,data)
Value=x(1).*data(:,2)+...
x(2).*log(data(:,3))+...
x(3).*abs(data(:,4))+...
x(4);
end
I would prefer to not use an anonymous function as the complexity of the model to which I will be fitting my future data to will only increase and an anonymous function would be messy to adjust as the regression model matures.
2.Define Initial Guess Row Vector x=[0,0,0,0]
3.Define optimization problem (referring to value data & x,y,z data contained in columns of SampleData.csv file) as a minimization problem trying to minimize a cost function defined as:
Cost=sum((FittingFunction(x,data)-data(:,1)).^2);
4. Pass optimization problem to a Genetic Algorithm routine with a hybrid function included using fminunc.
5. Create a MultiStart Optimization Object and Start a pool of workers.
lowerBounds for MultiStart =[-Inf,-Inf,-Inf,-Inf]; upperBounds for MultiStart =[Inf,Inf,Inf,Inf];
Number of MultiStart Iterations= 5.
5. Run optimization in parallel.
I realize that the problem which I defined is quite complex in its definition. I am not an expert user of Matlab and may not realize that my approach to solving this problem and the requirements (using the genetic algorithm, parallel processing, constraining coefficient ranges, and doing all of this using a MultiStart approach) for the fitting process may be unachievable.
I am using the serial port to read numbers from the arduino encoder. I did drawing a chart in app designer but in the X axis I only have the number of the next displayed number. I would like to see the time after which the number appeared in the X axis. The first number is e.g. 5 and in the x axis its time is 0, the next number 6 in the x axis appeared after 120ms and wants this time on the X axis.
delete(instrfind({'Port'},{app.PORT}))
app.x=serial(app.PORT,'BAUD',9600);
flushinput(app.x);
fopen(app.x); % otwarcie portu szeregowego
for i=1:app.Zakres.Value
drawnow
if app.Z == 1
break
end
h = str2num(fscanf(app.x));
app.aPolozenie.Value = h;
s = [s,h];
plot(app.UIAxes,s);
app.UIAxes.YLim = [ app.Od.Value app.Do.Value];
app.UIAxes.XLim = [0 app.Zakres.Value];
pause(.0001);
app.Zatrzymaj
end
end
This is my current status:
I do not know how to set up the fitting routine to use the Genetic Algorithm; my code is currently using lsqcurvefit, because this was the only way that I could figure out how to instantiate the matlab optimization problem object using the createOptimProblem() constructor.
I understand that lsqcurvefit cannot perform constrained optimization, but the Genetic Algorithm approach can do that; any help with setting up this problem using the genetic approach would be greatly appreciated, even if it is without the use of MultiStart for now.
As I am currently not using the Genetic Algorithm, I am not forcing the optimization solver to use the 'HybridFunction','on' option.
I am aware of the fact that the Global Optimization Toolbox has two options for finding global minima: GlobalSearch and MultiStart. I have decided to use MultiStart because according to the following article: http://www.mathworks.com/help/gads/how-globalsearch-and-multistart-work.html#bsc9eec MultiStart Can be setup in parallel on a multicore processor, while GlobalSearch cannot.
I am not sure if MultiStart or GlobalSearch can be setup to run with a Genetic Algorithm...
the MinGW Support Package is still shown as installed.
Why does MATLAB not detect the MinGW compiler anymore after a restart?
When installing the MinGW compiler, the environment variable MW_MINGW64_LOC is set with the path to the MinGW installation folder. On some systems where users have limited privileges, there may be policies in place preventing environment variables from being set. If this environment variable is not staying set following the installation, or after restarting MATLAB, the behavior described above may occur.
Here is my current code (requires the data.mat file attached to my posting):
clc
clear variables
%%Loading Measurement Data File
load('data.mat')
%%Defining function to which the data will be fit to
% I would like to move away from using the anonymous function,
% and move to using the function file defined in the directory but I don't
% know how to pass a function file to the createOptimProblem function call.
fitfcn1 = @(x,data)x(1).*data.x+x(2).*log(data.y)+abs(data.z).*x(3)+x(4);
%%Defining lower and upper bounds for MultiStart procedure
lb1 = [-Inf,-Inf,-Inf,-Inf];
ub1 = [Inf,Inf,Inf,Inf];
%%Creating row vector for intial guess to optimization routine
p01 = 0*ones(1,4);
%%Defining optimization problem object
% Currently running lsqcurvefit, but I need to move to the genetic
% algorythm approach. I do not understand how to setup a genetic alorythm
% data fitting routine in matlab using the GA functionality built into the
% global optimization toolbox.
problem1 = createOptimProblem('lsqcurvefit','x0',p01,'objective',fitfcn1,...
'lb',lb1,'ub',ub1,'xdata',data,'ydata',data.value);
%%Creating live fitting progress plot
ms1 = MultiStart('PlotFcns',@gsplotbestf);
%%Running MultiStart Optimization Routine
[xmulti1,errormulti1] = run(ms1,problem1,5)
This is my current status:
I do not know how to set up the fitting routine to use the Genetic Algorithm; my code is currently using lsqcurvefit, because this was the only way that I could figure out how to instantiate the matlab optimization problem object using the createOptimProblem() constructor.
I understand that lsqcurvefit cannot perform constrained optimization, but the Genetic Algorithm approach can do that; any help with setting up this problem using the genetic approach would be greatly appreciated, even if it is without the use of MultiStart for now.
As I am currently not using the Genetic Algorithm, I am not forcing the optimization solver to use the 'HybridFunction','on' option.
I am aware of the fact that the Global Optimization Toolbox has two options for finding global minima: GlobalSearch and MultiStart. I have decided to use MultiStart because according to the following article: http://www.mathworks.com/help/gads/how-globalsearch-and-multistart-work.html#bsc9eec MultiStart Can be setup in parallel on a multicore processor, while GlobalSearch cannot.
I am not sure if MultiStart or GlobalSearch can be setup to run with a Genetic Algorithm...
Can someone help on this? I'm sure it is straight forward but getting stumped. I would simply like to add two matrices together, element-wise, ignoring the NaNs. I realize one solution is to replace NaNs with zeros but I have some reported zeros that I want to be able to later identify. A solution to that is to set any real zeros to extremely small numbers. Rather than doing the above I am wondering if there is any other way to ignoring the NaNs -- I know of sum(...,'omitnan') and nansum() but they work on one matrix or if I concatenate the two matrices together then they aggregate either all rows or all columns depending on the dimension I select.
For example: A = ones(10,3); B = ones(10,3);
% inserting some NaNs and zeros A([1 6 10],1) = NaN; A([3 7],[2 3]) = NaN; B([3 7],2) = 0;
C = A + B;
I would like C = [1 2 2; 2 2 2; 2 0 1; 2 2 2; 2 2 2; 1 2 2; 2 0 1; 2 2 2; 2 2 2; 1 2 2]
I realize that the problem which I defined is quite complex in its definition. I am not an expert user of Matlab and may not realize that my approach to solving this problem and the requirements (using the genetic algorithm, parallel processing, constraining coefficient ranges, and doing all of this using a MultiStart approach) for the fitting process may be unachievable.
After installing the "MATLAB Support for MinGW-w64 C/C++ Compiler" support package, the command
>> mex -setup
reports that the compiler is correctly installed. However, when I restart MATLAB, the same command does not detect it as installed anymore.
When I check the Add-On Explorer, or run the command
>> matlabshared.supportpkg.getInstalled
the MinGW Support Package is still shown as installed.
Why does MATLAB not detect the MinGW compiler anymore after a restart?
When installing the MinGW compiler, the environment variable MW_MINGW64_LOC is set with the path to the MinGW installation folder. On some systems where users have limited privileges, there may be policies in place preventing environment variables from being set. If this environment variable is not staying set following the installation, or after restarting MATLAB, the behavior described above may occur.
Running the 'mex -setup' command in verbose mode
>> mex -setup -v
will display whether the MW_MINGW64_LOC environment variable is set. If this is not the case, the output will look as shown below:
... Looking for compiler 'MinGW64 Compiler (C)' ...
... Looking for environment variable 'MW_MINGW64_LOC' ...No.
The solution is to have an administrator set the environment variable. On Windows 10, you find this at:
Control Panel > System and Security > System > Advanced system settings > Environment Variables... > System variables: New...
The environment variable should have the following name and value:
Variable Name: MW_MINGW64_LOC
Variable Value: <SupportPackageRoot>\3P.instrset\mingw_w64.instrset
where <SupportPackage Root> is the output received for the command:
>> matlabshared.supportpkg.getSupportPackageRoot
Before the loop:
start_time = datetime('now');
rel_times = [];
In the loop, after
s = [s,h];
add
dt = milliseconds(datetime('now') - start_time);
rel_times = [rel_times, dt];
and change
plot(app.UIAxes,s);
to
plot(app.UIAxes, rel_times, s);
Note that performance of your application will get worse and worse over time, due to the way that you keep extending the s and rel_time arrays. Consider using a fixed-size buffer. Consider using animatedline() especially with a maximum number of points.
The Fixed-Point Tool collects ranges and proposes data types by data type groups rather than individual blocks.
A Data type group is a collection of block paths that need to have the same data type. If they don’t, Simulink will throw a data type mismatch error.
For instance, the output of the gain and the input to the subsystem need to have the same data type (they belong to the same data type group). Otherwise Simulink will throw a data type mismatch error. You can try this by changing the data type of the gain in the attached model to single.
For more details on the data type group, please refer to the documentation link below:
https://www.mathworks.com/help/fixedpoint/ug/data-type-propagation-errors-after-applying-proposed-data-types.html
All the shared ranges are an aggregation of the data type group ranges. In this case, shared simulation range is the aggregate of the simulation ranges of the data type group and similarly the shared design range is an aggregate of the design ranges of the group.
Fixed Point Tool proposes a data type that can accommodate all these shared ranges for the group.You can infact click the link at the bottom of the Result Details pane to highlight all the members of the data type group.
I am not concerned with the computational time required for the genetic approach, as, for now, I am just trying to develop a methodology for fitting complex, non-linear/non-smooth, functions using the various features available in Matlab's Global Optimization toolbox. The complexity and non-linearity of my function (presented below) will greatly increase in the near future.
The function which I am trying to fit my data to is defined as following:
VALUE=a1*x+a2*ln(y)+a3*abs(z)+a4
With: a1,a2,a3,a4 being the regression model's unknown coefficients
The following optimization constraints need to be imposed on the coefficients of the function:
a3<0; a4>0; a1*a2<0;
The data to which I am trying to fit my function to is presented in the attached SampleData.csv file. The file contains column labels which define the measured value and x,y,z parameters.
My initial guesses for the values of a1,a2,a3,a4 are defined as a row vector: [0,0,0,0].
I would like to learn how to set this problem up using MultiStart and parallel processing. I would like to use parallel processing for the MultiStart process, as well as to include a Hybrid Function, if such an operation is possible.
The work flow which I would like to achieve should be similar to:
1. Define Function (referring to x,y,z data contained in columns of SampleData.csv file) :
function [ Value ] = FittingFunction(x,data)
Value=x(1).*data(:,2)+...
x(2).*log(data(:,3))+...
x(3).*abs(data(:,4))+...
x(4);
end
I would prefer to not use an anonymous function as the complexity of the model to which I will be fitting my future data to will only increase and an anonymous function would be messy to adjust as the regression model matures.
2.Define Initial Guess Row Vector x=[0,0,0,0]
3.Define optimization problem (referring to value data & x,y,z data contained in columns of SampleData.csv file) as a minimization problem trying to minimize a cost function defined as:
Cost=sum((FittingFunction(x,data)-data(:,1)).^2);
4. Pass optimization problem to a Genetic Algorithm routine with a hybrid function included using fminunc.
5. Create a MultiStart Optimization Object and Start a pool of workers.
lowerBounds for MultiStart =[-Inf,-Inf,-Inf,-Inf]; upperBounds for MultiStart =[Inf,Inf,Inf,Inf];
Number of MultiStart Iterations= 5.
5. Run optimization in parallel.
I realize that the problem which I defined is quite complex in its definition. I am not an expert user of Matlab and may not realize that my approach to solving this problem and the requirements (using the genetic algorithm, parallel processing, constraining coefficient ranges, and doing all of this using a MultiStart approach) for the fitting process may be unachievable.
I am using the serial port to read numbers from the arduino encoder. I did drawing a chart in app designer but in the X axis I only have the number of the next displayed number. I would like to see the time after which the number appeared in the X axis. The first number is e.g. 5 and in the x axis its time is 0, the next number 6 in the x axis appeared after 120ms and wants this time on the X axis.
delete(instrfind({'Port'},{app.PORT}))
app.x=serial(app.PORT,'BAUD',9600);
flushinput(app.x);
fopen(app.x); % otwarcie portu szeregowego
for i=1:app.Zakres.Value
drawnow
if app.Z == 1
break
end
h = str2num(fscanf(app.x));
app.aPolozenie.Value = h;
s = [s,h];
plot(app.UIAxes,s);
app.UIAxes.YLim = [ app.Od.Value app.Do.Value];
app.UIAxes.XLim = [0 app.Zakres.Value];
pause(.0001);
app.Zatrzymaj
end
end
This is my current status:
I do not know how to set up the fitting routine to use the Genetic Algorithm; my code is currently using lsqcurvefit, because this was the only way that I could figure out how to instantiate the matlab optimization problem object using the createOptimProblem() constructor.
I understand that lsqcurvefit cannot perform constrained optimization, but the Genetic Algorithm approach can do that; any help with setting up this problem using the genetic approach would be greatly appreciated, even if it is without the use of MultiStart for now.
As I am currently not using the Genetic Algorithm, I am not forcing the optimization solver to use the 'HybridFunction','on' option.
I am aware of the fact that the Global Optimization Toolbox has two options for finding global minima: GlobalSearch and MultiStart. I have decided to use MultiStart because according to the following article: http://www.mathworks.com/help/gads/how-globalsearch-and-multistart-work.html#bsc9eec MultiStart Can be setup in parallel on a multicore processor, while GlobalSearch cannot.
I am not sure if MultiStart or GlobalSearch can be setup to run with a Genetic Algorithm...
Here is my current code (requires the data.mat file attached to my posting):
clc
clear variables
%%Loading Measurement Data File
load('data.mat')
%%Defining function to which the data will be fit to
% I would like to move away from using the anonymous function,
% and move to using the function file defined in the directory but I don't
% know how to pass a function file to the createOptimProblem function call.
fitfcn1 = @(x,data)x(1).*data.x+x(2).*log(data.y)+abs(data.z).*x(3)+x(4);
%%Defining lower and upper bounds for MultiStart procedure
lb1 = [-Inf,-Inf,-Inf,-Inf];
ub1 = [Inf,Inf,Inf,Inf];
%%Creating row vector for intial guess to optimization routine
p01 = 0*ones(1,4);
%%Defining optimization problem object
% Currently running lsqcurvefit, but I need to move to the genetic
% algorythm approach. I do not understand how to setup a genetic alorythm
% data fitting routine in matlab using the GA functionality built into the
% global optimization toolbox.
problem1 = createOptimProblem('lsqcurvefit','x0',p01,'objective',fitfcn1,...
'lb',lb1,'ub',ub1,'xdata',data,'ydata',data.value);
%%Creating live fitting progress plot
ms1 = MultiStart('PlotFcns',@gsplotbestf);
%%Running MultiStart Optimization Routine
[xmulti1,errormulti1] = run(ms1,problem1,5)
This is my current status:
I do not know how to set up the fitting routine to use the Genetic Algorithm; my code is currently using lsqcurvefit, because this was the only way that I could figure out how to instantiate the matlab optimization problem object using the createOptimProblem() constructor.
I understand that lsqcurvefit cannot perform constrained optimization, but the Genetic Algorithm approach can do that; any help with setting up this problem using the genetic approach would be greatly appreciated, even if it is without the use of MultiStart for now.
As I am currently not using the Genetic Algorithm, I am not forcing the optimization solver to use the 'HybridFunction','on' option.
I am aware of the fact that the Global Optimization Toolbox has two options for finding global minima: GlobalSearch and MultiStart. I have decided to use MultiStart because according to the following article: http://www.mathworks.com/help/gads/how-globalsearch-and-multistart-work.html#bsc9eec MultiStart Can be setup in parallel on a multicore processor, while GlobalSearch cannot.
I am not sure if MultiStart or GlobalSearch can be setup to run with a Genetic Algorithm...
Can someone help on this? I'm sure it is straight forward but getting stumped. I would simply like to add two matrices together, element-wise, ignoring the NaNs. I realize one solution is to replace NaNs with zeros but I have some reported zeros that I want to be able to later identify. A solution to that is to set any real zeros to extremely small numbers. Rather than doing the above I am wondering if there is any other way to ignoring the NaNs -- I know of sum(...,'omitnan') and nansum() but they work on one matrix or if I concatenate the two matrices together then they aggregate either all rows or all columns depending on the dimension I select.
For example: A = ones(10,3); B = ones(10,3);
% inserting some NaNs and zeros A([1 6 10],1) = NaN; A([3 7],[2 3]) = NaN; B([3 7],2) = 0;
C = A + B;
I would like C = [1 2 2; 2 2 2; 2 0 1; 2 2 2; 2 2 2; 1 2 2; 2 0 1; 2 2 2; 2 2 2; 1 2 2]
I realize that the problem which I defined is quite complex in its definition. I am not an expert user of Matlab and may not realize that my approach to solving this problem and the requirements (using the genetic algorithm, parallel processing, constraining coefficient ranges, and doing all of this using a MultiStart approach) for the fitting process may be unachievable.
After installing the "MATLAB Support for MinGW-w64 C/C++ Compiler" support package, the command
>> mex -setup
reports that the compiler is correctly installed. However, when I restart MATLAB, the same command does not detect it as installed anymore.
When I check the Add-On Explorer, or run the command
>> matlabshared.supportpkg.getInstalled
the MinGW Support Package is still shown as installed.
Why does MATLAB not detect the MinGW compiler anymore after a restart?
When installing the MinGW compiler, the environment variable MW_MINGW64_LOC is set with the path to the MinGW installation folder. On some systems where users have limited privileges, there may be policies in place preventing environment variables from being set. If this environment variable is not staying set following the installation, or after restarting MATLAB, the behavior described above may occur.
Running the 'mex -setup' command in verbose mode
>> mex -setup -v
will display whether the MW_MINGW64_LOC environment variable is set. If this is not the case, the output will look as shown below:
... Looking for compiler 'MinGW64 Compiler (C)' ...
... Looking for environment variable 'MW_MINGW64_LOC' ...No.
The solution is to have an administrator set the environment variable. On Windows 10, you find this at:
Control Panel > System and Security > System > Advanced system settings > Environment Variables... > System variables: New...
The environment variable should have the following name and value:
Variable Name: MW_MINGW64_LOC
Variable Value: <SupportPackageRoot>\3P.instrset\mingw_w64.instrset
where <SupportPackage Root> is the output received for the command:
>> matlabshared.supportpkg.getSupportPackageRoot
Before the loop:
start_time = datetime('now');
rel_times = [];
In the loop, after
s = [s,h];
add
dt = milliseconds(datetime('now') - start_time);
rel_times = [rel_times, dt];
and change
plot(app.UIAxes,s);
to
plot(app.UIAxes, rel_times, s);
Note that performance of your application will get worse and worse over time, due to the way that you keep extending the s and rel_time arrays. Consider using a fixed-size buffer. Consider using animatedline() especially with a maximum number of points.
The Fixed-Point Tool collects ranges and proposes data types by data type groups rather than individual blocks.
A Data type group is a collection of block paths that need to have the same data type. If they don’t, Simulink will throw a data type mismatch error.
For instance, the output of the gain and the input to the subsystem need to have the same data type (they belong to the same data type group). Otherwise Simulink will throw a data type mismatch error. You can try this by changing the data type of the gain in the attached model to single.
For more details on the data type group, please refer to the documentation link below:
https://www.mathworks.com/help/fixedpoint/ug/data-type-propagation-errors-after-applying-proposed-data-types.html
All the shared ranges are an aggregation of the data type group ranges. In this case, shared simulation range is the aggregate of the simulation ranges of the data type group and similarly the shared design range is an aggregate of the design ranges of the group.
Fixed Point Tool proposes a data type that can accommodate all these shared ranges for the group.You can infact click the link at the bottom of the Result Details pane to highlight all the members of the data type group.
I am not concerned with the computational time required for the genetic approach, as, for now, I am just trying to develop a methodology for fitting complex, non-linear/non-smooth, functions using the various features available in Matlab's Global Optimization toolbox. The complexity and non-linearity of my function (presented below) will greatly increase in the near future.
The function which I am trying to fit my data to is defined as following:
VALUE=a1*x+a2*ln(y)+a3*abs(z)+a4
With: a1,a2,a3,a4 being the regression model's unknown coefficients
The following optimization constraints need to be imposed on the coefficients of the function:
a3<0; a4>0; a1*a2<0;
The data to which I am trying to fit my function to is presented in the attached SampleData.csv file. The file contains column labels which define the measured value and x,y,z parameters.
My initial guesses for the values of a1,a2,a3,a4 are defined as a row vector: [0,0,0,0].
I would like to learn how to set this problem up using MultiStart and parallel processing. I would like to use parallel processing for the MultiStart process, as well as to include a Hybrid Function, if such an operation is possible.
The work flow which I would like to achieve should be similar to:
1. Define Function (referring to x,y,z data contained in columns of SampleData.csv file) :
function [ Value ] = FittingFunction(x,data)
Value=x(1).*data(:,2)+...
x(2).*log(data(:,3))+...
x(3).*abs(data(:,4))+...
x(4);
end
I would prefer to not use an anonymous function as the complexity of the model to which I will be fitting my future data to will only increase and an anonymous function would be messy to adjust as the regression model matures.
2.Define Initial Guess Row Vector x=[0,0,0,0]
3.Define optimization problem (referring to value data & x,y,z data contained in columns of SampleData.csv file) as a minimization problem trying to minimize a cost function defined as:
Cost=sum((FittingFunction(x,data)-data(:,1)).^2);
4. Pass optimization problem to a Genetic Algorithm routine with a hybrid function included using fminunc.
5. Create a MultiStart Optimization Object and Start a pool of workers.
lowerBounds for MultiStart =[-Inf,-Inf,-Inf,-Inf]; upperBounds for MultiStart =[Inf,Inf,Inf,Inf];
Number of MultiStart Iterations= 5.
5. Run optimization in parallel.
I realize that the problem which I defined is quite complex in its definition. I am not an expert user of Matlab and may not realize that my approach to solving this problem and the requirements (using the genetic algorithm, parallel processing, constraining coefficient ranges, and doing all of this using a MultiStart approach) for the fitting process may be unachievable.
I am using the serial port to read numbers from the arduino encoder. I did drawing a chart in app designer but in the X axis I only have the number of the next displayed number. I would like to see the time after which the number appeared in the X axis. The first number is e.g. 5 and in the x axis its time is 0, the next number 6 in the x axis appeared after 120ms and wants this time on the X axis.
delete(instrfind({'Port'},{app.PORT}))
app.x=serial(app.PORT,'BAUD',9600);
flushinput(app.x);
fopen(app.x); % otwarcie portu szeregowego
for i=1:app.Zakres.Value
drawnow
if app.Z == 1
break
end
h = str2num(fscanf(app.x));
app.aPolozenie.Value = h;
s = [s,h];
plot(app.UIAxes,s);
app.UIAxes.YLim = [ app.Od.Value app.Do.Value];
app.UIAxes.XLim = [0 app.Zakres.Value];
pause(.0001);
app.Zatrzymaj
end
end
This is my current status:
I do not know how to set up the fitting routine to use the Genetic Algorithm; my code is currently using lsqcurvefit, because this was the only way that I could figure out how to instantiate the matlab optimization problem object using the createOptimProblem() constructor.
I understand that lsqcurvefit cannot perform constrained optimization, but the Genetic Algorithm approach can do that; any help with setting up this problem using the genetic approach would be greatly appreciated, even if it is without the use of MultiStart for now.
As I am currently not using the Genetic Algorithm, I am not forcing the optimization solver to use the 'HybridFunction','on' option.
I am aware of the fact that the Global Optimization Toolbox has two options for finding global minima: GlobalSearch and MultiStart. I have decided to use MultiStart because according to the following article: http://www.mathworks.com/help/gads/how-globalsearch-and-multistart-work.html#bsc9eec MultiStart Can be setup in parallel on a multicore processor, while GlobalSearch cannot.
I am not sure if MultiStart or GlobalSearch can be setup to run with a Genetic Algorithm...
Here is my current code (requires the data.mat file attached to my posting):
clc
clear variables
%%Loading Measurement Data File
load('data.mat')
%%Defining function to which the data will be fit to
% I would like to move away from using the anonymous function,
% and move to using the function file defined in the directory but I don't
% know how to pass a function file to the createOptimProblem function call.
fitfcn1 = @(x,data)x(1).*data.x+x(2).*log(data.y)+abs(data.z).*x(3)+x(4);
%%Defining lower and upper bounds for MultiStart procedure
lb1 = [-Inf,-Inf,-Inf,-Inf];
ub1 = [Inf,Inf,Inf,Inf];
%%Creating row vector for intial guess to optimization routine
p01 = 0*ones(1,4);
%%Defining optimization problem object
% Currently running lsqcurvefit, but I need to move to the genetic
% algorythm approach. I do not understand how to setup a genetic alorythm
% data fitting routine in matlab using the GA functionality built into the
% global optimization toolbox.
problem1 = createOptimProblem('lsqcurvefit','x0',p01,'objective',fitfcn1,...
'lb',lb1,'ub',ub1,'xdata',data,'ydata',data.value);
%%Creating live fitting progress plot
ms1 = MultiStart('PlotFcns',@gsplotbestf);
%%Running MultiStart Optimization Routine
[xmulti1,errormulti1] = run(ms1,problem1,5)
This is my current status:
I do not know how to set up the fitting routine to use the Genetic Algorithm; my code is currently using lsqcurvefit, because this was the only way that I could figure out how to instantiate the matlab optimization problem object using the createOptimProblem() constructor.
I understand that lsqcurvefit cannot perform constrained optimization, but the Genetic Algorithm approach can do that; any help with setting up this problem using the genetic approach would be greatly appreciated, even if it is without the use of MultiStart for now.
As I am currently not using the Genetic Algorithm, I am not forcing the optimization solver to use the 'HybridFunction','on' option.
I am aware of the fact that the Global Optimization Toolbox has two options for finding global minima: GlobalSearch and MultiStart. I have decided to use MultiStart because according to the following article: http://www.mathworks.com/help/gads/how-globalsearch-and-multistart-work.html#bsc9eec MultiStart Can be setup in parallel on a multicore processor, while GlobalSearch cannot.
I am not sure if MultiStart or GlobalSearch can be setup to run with a Genetic Algorithm...
Can someone help on this? I'm sure it is straight forward but getting stumped. I would simply like to add two matrices together, element-wise, ignoring the NaNs. I realize one solution is to replace NaNs with zeros but I have some reported zeros that I want to be able to later identify. A solution to that is to set any real zeros to extremely small numbers. Rather than doing the above I am wondering if there is any other way to ignoring the NaNs -- I know of sum(...,'omitnan') and nansum() but they work on one matrix or if I concatenate the two matrices together then they aggregate either all rows or all columns depending on the dimension I select.
For example: A = ones(10,3); B = ones(10,3);
% inserting some NaNs and zeros A([1 6 10],1) = NaN; A([3 7],[2 3]) = NaN; B([3 7],2) = 0;
C = A + B;
I would like C = [1 2 2; 2 2 2; 2 0 1; 2 2 2; 2 2 2; 1 2 2; 2 0 1; 2 2 2; 2 2 2; 1 2 2]
I realize that the problem which I defined is quite complex in its definition. I am not an expert user of Matlab and may not realize that my approach to solving this problem and the requirements (using the genetic algorithm, parallel processing, constraining coefficient ranges, and doing all of this using a MultiStart approach) for the fitting process may be unachievable.
After installing the "MATLAB Support for MinGW-w64 C/C++ Compiler" support package, the command
>> mex -setup
reports that the compiler is correctly installed. However, when I restart MATLAB, the same command does not detect it as installed anymore.
When I check the Add-On Explorer, or run the command
>> matlabshared.supportpkg.getInstalled
the MinGW Support Package is still shown as installed.
Why does MATLAB not detect the MinGW compiler anymore after a restart?
When installing the MinGW compiler, the environment variable MW_MINGW64_LOC is set with the path to the MinGW installation folder. On some systems where users have limited privileges, there may be policies in place preventing environment variables from being set. If this environment variable is not staying set following the installation, or after restarting MATLAB, the behavior described above may occur.
Running the 'mex -setup' command in verbose mode
>> mex -setup -v
will display whether the MW_MINGW64_LOC environment variable is set. If this is not the case, the output will look as shown below:
... Looking for compiler 'MinGW64 Compiler (C)' ...
... Looking for environment variable 'MW_MINGW64_LOC' ...No.
The solution is to have an administrator set the environment variable. On Windows 10, you find this at:
Control Panel > System and Security > System > Advanced system settings > Environment Variables... > System variables: New...
The environment variable should have the following name and value:
Variable Name: MW_MINGW64_LOC
Variable Value: <SupportPackageRoot>\3P.instrset\mingw_w64.instrset
where <SupportPackage Root> is the output received for the command:
>> matlabshared.supportpkg.getSupportPackageRoot
Before the loop:
start_time = datetime('now');
rel_times = [];
In the loop, after
s = [s,h];
add
dt = milliseconds(datetime('now') - start_time);
rel_times = [rel_times, dt];
and change
plot(app.UIAxes,s);
to
plot(app.UIAxes, rel_times, s);
Note that performance of your application will get worse and worse over time, due to the way that you keep extending the s and rel_time arrays. Consider using a fixed-size buffer. Consider using animatedline() especially with a maximum number of points.
The Fixed-Point Tool collects ranges and proposes data types by data type groups rather than individual blocks.
A Data type group is a collection of block paths that need to have the same data type. If they don’t, Simulink will throw a data type mismatch error.
For instance, the output of the gain and the input to the subsystem need to have the same data type (they belong to the same data type group). Otherwise Simulink will throw a data type mismatch error. You can try this by changing the data type of the gain in the attached model to single.
For more details on the data type group, please refer to the documentation link below:
https://www.mathworks.com/help/fixedpoint/ug/data-type-propagation-errors-after-applying-proposed-data-types.html
All the shared ranges are an aggregation of the data type group ranges. In this case, shared simulation range is the aggregate of the simulation ranges of the data type group and similarly the shared design range is an aggregate of the design ranges of the group.
Fixed Point Tool proposes a data type that can accommodate all these shared ranges for the group.You can infact click the link at the bottom of the Result Details pane to highlight all the members of the data type group.
I am not concerned with the computational time required for the genetic approach, as, for now, I am just trying to develop a methodology for fitting complex, non-linear/non-smooth, functions using the various features available in Matlab's Global Optimization toolbox. The complexity and non-linearity of my function (presented below) will greatly increase in the near future.
The function which I am trying to fit my data to is defined as following:
VALUE=a1*x+a2*ln(y)+a3*abs(z)+a4
With: a1,a2,a3,a4 being the regression model's unknown coefficients
The following optimization constraints need to be imposed on the coefficients of the function:
a3<0; a4>0; a1*a2<0;
The data to which I am trying to fit my function to is presented in the attached SampleData.csv file. The file contains column labels which define the measured value and x,y,z parameters.
My initial guesses for the values of a1,a2,a3,a4 are defined as a row vector: [0,0,0,0].
I would like to learn how to set this problem up using MultiStart and parallel processing. I would like to use parallel processing for the MultiStart process, as well as to include a Hybrid Function, if such an operation is possible.
The work flow which I would like to achieve should be similar to:
1. Define Function (referring to x,y,z data contained in columns of SampleData.csv file) :
function [ Value ] = FittingFunction(x,data)
Value=x(1).*data(:,2)+...
x(2).*log(data(:,3))+...
x(3).*abs(data(:,4))+...
x(4);
end
I would prefer to not use an anonymous function as the complexity of the model to which I will be fitting my future data to will only increase and an anonymous function would be messy to adjust as the regression model matures.
2.Define Initial Guess Row Vector x=[0,0,0,0]
3.Define optimization problem (referring to value data & x,y,z data contained in columns of SampleData.csv file) as a minimization problem trying to minimize a cost function defined as:
Cost=sum((FittingFunction(x,data)-data(:,1)).^2);
4. Pass optimization problem to a Genetic Algorithm routine with a hybrid function included using fminunc.
5. Create a MultiStart Optimization Object and Start a pool of workers.
lowerBounds for MultiStart =[-Inf,-Inf,-Inf,-Inf]; upperBounds for MultiStart =[Inf,Inf,Inf,Inf];
Number of MultiStart Iterations= 5.
5. Run optimization in parallel.
I realize that the problem which I defined is quite complex in its definition. I am not an expert user of Matlab and may not realize that my approach to solving this problem and the requirements (using the genetic algorithm, parallel processing, constraining coefficient ranges, and doing all of this using a MultiStart approach) for the fitting process may be unachievable.
I am using the serial port to read numbers from the arduino encoder. I did drawing a chart in app designer but in the X axis I only have the number of the next displayed number. I would like to see the time after which the number appeared in the X axis. The first number is e.g. 5 and in the x axis its time is 0, the next number 6 in the x axis appeared after 120ms and wants this time on the X axis.
delete(instrfind({'Port'},{app.PORT}))
app.x=serial(app.PORT,'BAUD',9600);
flushinput(app.x);
fopen(app.x); % otwarcie portu szeregowego
for i=1:app.Zakres.Value
drawnow
if app.Z == 1
break
end
h = str2num(fscanf(app.x));
app.aPolozenie.Value = h;
s = [s,h];
plot(app.UIAxes,s);
app.UIAxes.YLim = [ app.Od.Value app.Do.Value];
app.UIAxes.XLim = [0 app.Zakres.Value];
pause(.0001);
app.Zatrzymaj
end
end
This is my current status:
I do not know how to set up the fitting routine to use the Genetic Algorithm; my code is currently using lsqcurvefit, because this was the only way that I could figure out how to instantiate the matlab optimization problem object using the createOptimProblem() constructor.
I understand that lsqcurvefit cannot perform constrained optimization, but the Genetic Algorithm approach can do that; any help with setting up this problem using the genetic approach would be greatly appreciated, even if it is without the use of MultiStart for now.
As I am currently not using the Genetic Algorithm, I am not forcing the optimization solver to use the 'HybridFunction','on' option.
I am aware of the fact that the Global Optimization Toolbox has two options for finding global minima: GlobalSearch and MultiStart. I have decided to use MultiStart because according to the following article: http://www.mathworks.com/help/gads/how-globalsearch-and-multistart-work.html#bsc9eec MultiStart Can be setup in parallel on a multicore processor, while GlobalSearch cannot.
I am not sure if MultiStart or GlobalSearch can be setup to run with a Genetic Algorithm...
Here is my current code (requires the data.mat file attached to my posting):
clc
clear variables
%%Loading Measurement Data File
load('data.mat')
%%Defining function to which the data will be fit to
% I would like to move away from using the anonymous function,
% and move to using the function file defined in the directory but I don't
% know how to pass a function file to the createOptimProblem function call.
fitfcn1 = @(x,data)x(1).*data.x+x(2).*log(data.y)+abs(data.z).*x(3)+x(4);
%%Defining lower and upper bounds for MultiStart procedure
lb1 = [-Inf,-Inf,-Inf,-Inf];
ub1 = [Inf,Inf,Inf,Inf];
%%Creating row vector for intial guess to optimization routine
p01 = 0*ones(1,4);
%%Defining optimization problem object
% Currently running lsqcurvefit, but I need to move to the genetic
% algorythm approach. I do not understand how to setup a genetic alorythm
% data fitting routine in matlab using the GA functionality built into the
% global optimization toolbox.
problem1 = createOptimProblem('lsqcurvefit','x0',p01,'objective',fitfcn1,...
'lb',lb1,'ub',ub1,'xdata',data,'ydata',data.value);
%%Creating live fitting progress plot
ms1 = MultiStart('PlotFcns',@gsplotbestf);
%%Running MultiStart Optimization Routine
[xmulti1,errormulti1] = run(ms1,problem1,5)
This is my current status:
I do not know how to set up the fitting routine to use the Genetic Algorithm; my code is currently using lsqcurvefit, because this was the only way that I could figure out how to instantiate the matlab optimization problem object using the createOptimProblem() constructor.
I understand that lsqcurvefit cannot perform constrained optimization, but the Genetic Algorithm approach can do that; any help with setting up this problem using the genetic approach would be greatly appreciated, even if it is without the use of MultiStart for now.
As I am currently not using the Genetic Algorithm, I am not forcing the optimization solver to use the 'HybridFunction','on' option.
I am aware of the fact that the Global Optimization Toolbox has two options for finding global minima: GlobalSearch and MultiStart. I have decided to use MultiStart because according to the following article: http://www.mathworks.com/help/gads/how-globalsearch-and-multistart-work.html#bsc9eec MultiStart Can be setup in parallel on a multicore processor, while GlobalSearch cannot.
I am not sure if MultiStart or GlobalSearch can be setup to run with a Genetic Algorithm...
Can someone help on this? I'm sure it is straight forward but getting stumped. I would simply like to add two matrices together, element-wise, ignoring the NaNs. I realize one solution is to replace NaNs with zeros but I have some reported zeros that I want to be able to later identify. A solution to that is to set any real zeros to extremely small numbers. Rather than doing the above I am wondering if there is any other way to ignoring the NaNs -- I know of sum(...,'omitnan') and nansum() but they work on one matrix or if I concatenate the two matrices together then they aggregate either all rows or all columns depending on the dimension I select.
For example: A = ones(10,3); B = ones(10,3);
% inserting some NaNs and zeros A([1 6 10],1) = NaN; A([3 7],[2 3]) = NaN; B([3 7],2) = 0;
C = A + B;
I would like C = [1 2 2; 2 2 2; 2 0 1; 2 2 2; 2 2 2; 1 2 2; 2 0 1; 2 2 2; 2 2 2; 1 2 2]
I realize that the problem which I defined is quite complex in its definition. I am not an expert user of Matlab and may not realize that my approach to solving this problem and the requirements (using the genetic algorithm, parallel processing, constraining coefficient ranges, and doing all of this using a MultiStart approach) for the fitting process may be unachievable.
After installing the "MATLAB Support for MinGW-w64 C/C++ Compiler" support package, the command
>> mex -setup
reports that the compiler is correctly installed. However, when I restart MATLAB, the same command does not detect it as installed anymore.
When I check the Add-On Explorer, or run the command
>> matlabshared.supportpkg.getInstalled
the MinGW Support Package is still shown as installed.
Why does MATLAB not detect the MinGW compiler anymore after a restart?
When installing the MinGW compiler, the environment variable MW_MINGW64_LOC is set with the path to the MinGW installation folder. On some systems where users have limited privileges, there may be policies in place preventing environment variables from being set. If this environment variable is not staying set following the installation, or after restarting MATLAB, the behavior described above may occur.
Running the 'mex -setup' command in verbose mode
>> mex -setup -v
will display whether the MW_MINGW64_LOC environment variable is set. If this is not the case, the output will look as shown below:
... Looking for compiler 'MinGW64 Compiler (C)' ...
... Looking for environment variable 'MW_MINGW64_LOC' ...No.
The solution is to have an administrator set the environment variable. On Windows 10, you find this at:
Control Panel > System and Security > System > Advanced system settings > Environment Variables... > System variables: New...
rel_times = [rel_times, dt];
and change
plot(app.UIAxes,s);
to
plot(app.UIAxes, rel_times, s);
Note that performance of your application will get worse and worse over time, due to the way that you keep extending.
the MinGW Support Package is still shown as installed.
Why does MATLAB not detect the MinGW compiler anymore after a restart?
When installing the MinGW compiler, the environment variable MW_MINGW64_LOC is set with the path to the MinGW installation folder. On some systems where users have limited privileges, there may be policies in place preventing environment variables from being set. If this environment variable is not staying set following the installation, or after restarting MATLAB, the behavior described above may occur.
the MinGW Support Package is still shown as installed.
Why does MATLAB not detect the MinGW compiler anymore after a restart?
When installing the MinGW compiler, the environment variable MW_MINGW64_LOC is set with the path to the MinGW installation folder. On some systems where users have limited privileges, there may be policies in place preventing environment variables from being set. If this environment variable is not staying set following the installation, or after restarting MATLAB, the behavior described above may occur.
h = str2num(fscanf(app.x));
app.aPolozenie.Value = h;
s = [s,h];
plot(app.UIAxes,s);
app.UIAxes.YLim = [ app.Od.Value app.Do.Value];
app.UIAxes.XLim = [0 app.Zakres.Value];
pause(.0001);
app.Zatrzymaj
end
David Hastanahttps://in.mathworks.com/matlabcentral/profile/authors/17599357-david-hastanatag:in.mathworks.com,2005:Question/5069472020-02-22T09:30:42Z2020-02-24T23:01:31ZExtract numbers from lines in a txt file. Onset times from experimental data.Hi,
This problem should be familiar to people working with behavioral data, but I was unable to find a previous answer that would work for me.
I am trying to extract the onset times of certain conditions during an experiment.
The data is organised as in the enclosed file. I want to extract the lines starting with:
'WaitForScanner.OnsetTime'
'Tune.OnsetTime'
and
'ImagineMelody.OnsetTime'
and then extract the numbers at the end of these lines (5-digit onset times in ms) as variables,
work with them a bit in matlab: subtract scanneronset from tuneonset and imagineonset, and convert them to seconds,
and output them in two separate txt files (tuneonset.txt and imagine.txt).
When that works for one subject, I plan to loop over many subjects and also different sessions per subject (different txt file, same principle).
Best,
Andreas
Andreas Voldstadhttps://in.mathworks.com/matlabcentral/profile/authors/17599695-andreas-voldstadtag:in.mathworks.com,2005:Question/5073302020-02-24T22:20:17Z2020-02-24T22:55:46ZCreate A loop for large DataHi there,
I am trying to make a misk that is have very large of dics(while holes), this maks is best of specific rows, coles ans vales so it is not rundom things. I do have these values. However, when I try to build up the mask, it will take for long time to do this values manuly. So, I tried to se if or loop for these vales but the reult did not shows uniform mask. look at the figure. As you can see, the discs are sorf double and not one disc as I want. So how I can do one disc in one location.
Here is the example of the code
rows = [r1, r2, r3 , ....];
coles = [c1, c2, c3, ....];
vales = [v1, v2, v3, ....];
for ii = rows
for ij = coles
for jj = vales
Z(ij,ii)= jj;
Z(ij-dr:ij+dr,ii-dr:ii+dr)=D;
end
end
end
figure;
imshow(Z);
%NOTE:
D is disc matrix as follows
r = 4;
dr = r-1; % radus of the disc
disk = strel('disk',r);
D = disk.Neighborhood;
and
Z is the zeros materix
Abdulrahman Otaibihttps://in.mathworks.com/matlabcentral/profile/authors/17463733-abdulrahman-otaibitag:in.mathworks.com,2005:Question/2306192015-07-21T15:05:03Z2020-02-24T22:53:00ZCount word frequency, please helpI have a column which contain cells each contain a text, and i want to *count the frequency of each word*
I write this code - which works - to count the word frequency and sort it
str = alldata{:,51};
C = regexp((str),' ','split')';
[val,idxC, idxV] = unique(C);
n = accumarray(idxV,1);
m = [n idxC] ; %n occurences for word C(idxC)
y = [val num2cell(n)]; % t without sort
[~, so]= sort(n,'descend'); % sort the frequencies descend and rest alphabet
words= val(so); % sort words by frequency
freq= n(so); % sort frequency
z = [words num2cell(freq)]; % show words with frequency sort
it give me a good answer which:
<</matlabcentral/answers/uploaded_files/34444/word%20freq.jpg>>
this work on the first cell only, but i want to make the word frequency to the whole cells
<</matlabcentral/answers/uploaded_files/34445/whole%20file.jpg>>
I try this:
j=1;
for i=1:size(alldata,1)
fid(j,1) = alldata(i,51);
C(k,1) = regexp((fid(j,1)),' ','split')';
[val{k},idxC{k}, idxV{k}] = unique(C{k});
n{k} = accumarray(idxV(k),1);
j=j+1;
end
m = [n idxC] ;
y = [val num2cell(n)];
[~, so] = sort(n,'descend');% s= sort(n);
words = val(so);
freq = n(so);
z = [words num2cell(freq)];
but it didn't work , it seems i have to merge all cells first.
* | *how i can get the word frequency of the whole file ?* | *Amr Hashemhttps://in.mathworks.com/matlabcentral/profile/authors/6506616-amr-hashemtag:in.mathworks.com,2005:Question/5073212020-02-24T21:16:09Z2020-02-24T22:52:05ZHow to create multiple matlabFunctions from an array containing symbolic expressions?I have an array containing a number of symbolic expressions, for example:
syms x y z
expressions = [x, y, z, x^2, y^2, z^2, x*y, x*z, y*z];
How can I create a matlabFunction for each expression without manually defining each one?
Is it possible to create an array of matlabFunctions?
ThanksNikhil Shahhttps://in.mathworks.com/matlabcentral/profile/authors/9186893-nikhil-shahtag:in.mathworks.com,2005:Question/282812012-02-07T05:35:16Z2020-02-24T22:49:43Zpolar fourier transformcan anyone help me with the matlab code for polar fourier tranform.i have to apply this transform to the binary image. sathyahttps://in.mathworks.com/matlabcentral/profile/authors/3217459-sathyatag:in.mathworks.com,2005:Question/5073322020-02-24T22:44:16Z2020-02-24T22:44:16ZVariable Frequency Drive With Sinusoidal PWM InverterHi everyone,
I created a model to simulate a variable frequency drive with closed loop Volt/Herz control. I am not managing to obtain proper results.
I think I have a probelm with setting the simulation time properly and making every task to work at the proper rate.
Please find the model attached and let me know if you are able to solve my problem.
Thank you in advance.
Adriano Arcihttps://in.mathworks.com/matlabcentral/profile/authors/13898522-adriano-arcitag:in.mathworks.com,2005:Question/5073142020-02-24T20:07:17Z2020-02-24T22:34:01ZError using trustnleqn (line 28)Hello everyone,
I'm trying to solve non linear equations system using fsolve. I'm beginner in matlab I just have no idea what's going on with my program when I tried to run it, there's an error message in the command window:
function F = BEB(x)
n = 50; %number of stations
F(1) = x(1) - (2) / (1-x(2))*((1+x(2))+ 16*(1+2*x(2))+ ((x(2)^3)/(1-2*x(2)))*((x(2)/1-x(2))-((x(2)/1-x(2))^6)/((x(2)/1-x(2))^2))*((64*x(2)^3)/1-3*x(2))*(2*(x(2)/1-x(2))-((2*(x(2)/1-x(2)))^6))/(2*(x(2)/1-x(2))^2));
F(2) = (1-x(1))^n + x(2) -1;
i run it:
fun = @BEB
x0 = [0 0]
x = fsolve (fun, x0)Amirul Hezryhttps://in.mathworks.com/matlabcentral/profile/authors/17625431-amirul-hezrytag:in.mathworks.com,2005:Question/5071782020-02-24T04:58:00Z2020-02-24T22:18:37Zhow to use buitin functions like fcm in gui?I am trying to implment a GUI for a project. I have to use the fcm builtin function . How to call this function from the gui from the callback and display back the results and
as well plot the image of the dataset.
Maddiehttps://in.mathworks.com/matlabcentral/profile/authors/15124959-maddietag:in.mathworks.com,2005:Question/5073102020-02-24T19:55:02Z2020-02-24T22:12:49ZDivide a 3D shape into equal-volume subregions?I have a 3D shape that can be approximated with Delauny triangularization or a convex hull. I would like to divide the shape into a certain number of equal-volume subregions; ideally each subregion would have nearly the same surface area. Here are a couple places I looked but did not find a solution,
Object functions that you can use on a Delauny triangularization object, a polyshape object, or an alphashape object
File exchange polygon2voxel
Below is an example conical 3D shape. How can I divide the volume enclosed by the shape into 100 equal-volume subregions? The subregions can all be entirely enclosed by the hull, leaving some of the shape's volume unenclosed by subregions, as if you were to fill a conical container with ice cubes.
Is the best way just to grid the region in xyz and adjust the grid spacing until I get 100 cubes?
load('seamount.mat', 'x', 'y', 'z'); % Generic data that comes with Matlab; contains 3D points
DT = delaunayTriangulation(x,y,z); % 3D triangulization of points
[C, volHull] = convexHull(DT); % Compute convex hull, which is cone-shaped
figure('Name', 'Convex Hull');
hPatch = trisurf(C,DT.Points(:,1),DT.Points(:,2),DT.Points(:,3), ...
'FaceAlpha', 0.1);
% Now how to find 100 subregions of equal volume within this shape
KAEhttps://in.mathworks.com/matlabcentral/profile/authors/9495793-kaetag:in.mathworks.com,2005:Question/5072402020-02-24T13:10:58Z2020-02-24T22:07:13ZTake the sum of an array until a limit is reached determined by a vector of the same lengthI have a scatter graph made from two arrays of equal length,
How may I take the sum of the intensities per an arbituary track length of 10mm? I know it might have something to do with cumsum, any help would be much apprieciated, cheers.
For any example maybe consider these two smaller arrays:
TL = [1,1,2,2,1,3,3,3,4,5,5];
I = [1,1,1,1,3,3,1,6,6,6,5];HenT2020https://in.mathworks.com/matlabcentral/profile/authors/17204733-hent2020tag:in.mathworks.com,2005:Question/4666142019-06-12T05:27:07Z2020-02-24T22:03:42ZHow to plot the real time data from arduino?I have an Arduino program loaded to the Arduino. I want to plot the real time data from arduino in the MATLAB too. My MATLAB program can get the data from the Arduino board and plot successfully. However, it seems the MATLAB will write something to the Arduino board to override the Arduino program. Is it true? If the answer is positive, may I have a help that how can I get the data from Arduino without affecting the Arduino program? (P.S. both Arduino program and MATLAB program will read the same pin such as A0). Many thanks!Tommy Fuhttps://in.mathworks.com/matlabcentral/profile/authors/13522412-tommy-futag:in.mathworks.com,2005:Question/5073272020-02-24T22:02:34Z2020-02-24T22:02:34ZBlend function in scatter or scatter3?When zooming out from a large coloured point cloud (each point in the cloud has a specific colour representing a property, the pointsize is 1 as the alpha) in either scatter or scatter3, the colours change (become darker) as more than one point occupies a pixel. Clearly there must be a blend function to combine the colours of these opaque points. Is it possible to find out what this function is? davidwriterhttps://in.mathworks.com/matlabcentral/profile/authors/4157952-davidwritertag:in.mathworks.com,2005:Question/5072832020-02-24T17:04:21Z2020-02-24T21:58:33ZObtain single equation from a system of equations stored as an anonymous functionHi all,
I would like to ask if it is possible to use some sort of notation or other trick, such that I can obtain one of the two equations that I have stored in a system of anonymous functions.
In specific, I have a system of two equations, in the following anonymous function:
F = @(x) [x(1).*x(2).^2 + sin(x(2)) ; ...
cos(x(1)) + x(2).^3 ] ;
And I would like to obtain:
f = @(x) x(1,:).*x(2).^2 + sin(x(2))
Is it possible to do this by some sort of notation such as F.1, F{1}, etc.?Kostashttps://in.mathworks.com/matlabcentral/profile/authors/15803667-kostastag:in.mathworks.com,2005:Question/5073062020-02-24T19:42:24Z2020-02-24T21:58:05ZStackedplot with x-axis vectorHello,
I am very new and am struggling to get stackedplot to work at all.
I would like to use stackedplot to create some stacked line curves with a common x-axis. The x-axis should be wavelength values that I have as a column in my spreadsheet ('Channels'). The two line graphs should be intensity values of 'illite' and 'kaolinite', also listed in columns.
This is the code I have (with spreadsheet specifications removed):
close all
figure
tbl = readtable('___','Sheet','___');
head(tbl,2);
stackedplot({'Channel'},{'illite','kaolinite'});
I get the error:
Error using stackedplot (line 76)
Expected x to be one of these types:
datetime, duration, double, single, uint8, uint16,
uint32, uint64, int8, int16, int32, int64, logical
Error in stackedplottest (line 14)
stackedplot({'Channel'},{'illite','kaolinite'});
Please help :(Erin Gibbonshttps://in.mathworks.com/matlabcentral/profile/authors/15851216-erin-gibbonstag:in.mathworks.com,2005:Question/5073182020-02-24T21:05:43Z2020-02-24T21:58:00ZGlobal optimization of parameters in odeHi
I want to fit the solution of differential equation
dy/dt= -ay-by^2-cy^3
to my experimental data to optimize globally constants a, b and c .
I have used lsqcurvefit to do show but I cannot get these values of constant matching with the earlier values so I need to fit them globally by using Genetic algoritm.
How can I define the fit function (objective function)??
Here is the code I have so far.
% % % % % % % % experimental values
A=load('data.csv');
time=(A(1,150:end));
B=(A(691,150:end))';
data=B./min(B);
plot(time,data,'or')
% % % % % % % % % % Solving the differential equation and plotting experimental data vs solution of ode
tspan = [0 3000];
y0 = 1;
y01=1;
a=0.001;b=0.001;c=0.0001;
[t,y] = ode45(@(t,y) -a*y^3-b*y^2-c*y, tspan, y0);
plot(time,data,'or','Markersize',2)
hold on
plot(t,y,'-k','Color','magenta')
hold off
xlim([0 3000]);
legend('data','ode45')
Bibek Dhamihttps://in.mathworks.com/matlabcentral/profile/authors/12250893-bibek-dhamitag:in.mathworks.com,2005:Question/5073252020-02-24T21:50:51Z2020-02-24T21:50:51ZBalancing levels of audio signalsHi,
I have got two audio intervals named m_ref and m_test. The former consists of signal vector y1, and the latter consist of y1 + a variable level (in dB) of signal vector y2.
They are defined as follows:
m_ref = y1;
m_test = y1 + 10^(M.VAR/20)*y2;
I want to balance the loudness levels of m_test and m_ref so they are the same . E.g. using rms(x):
m_test = m_test / rms(m_test) * rms(m_ref);
Gives the error below:
Not enough input arguments.
Error in rms (line 24)
y = sqrt(mean(x.*conj(x), dim)); % works for complex vectors, too
Error in abs_threshold_colorationuser (line 26)
m_test = m_test / rms(m_test) * rms(m_ref);
Marius Tøndel Eliassenhttps://in.mathworks.com/matlabcentral/profile/authors/14712141-marius-tondel-eliassentag:in.mathworks.com,2005:Question/5073242020-02-24T21:50:16Z2020-02-24T21:50:16ZI need a source of pv model equations that in libraryHallo everyone.
I need a source paper of equations of photovoltaic model that exist in renewable energy library.
Please i need exactly one used, i do not want one with any small different.Mohammad alshamaahttps://in.mathworks.com/matlabcentral/profile/authors/15079783-mohammad-alshamaatag:in.mathworks.com,2005:Question/5070622020-02-23T09:52:33Z2020-02-24T21:49:15ZIs it possible to calculate the average Manhattan distance between a set of 2D points with one function?Is there an easier way to calculate the average Manhattan distance between a set of points easier than I have it in my code? I have a matrix, which contains a set of 2D points (the columns corespond to the x and y coordinates).
%for the first point
[idx,~]=dsearchn(isec(2:end,:),isec(1,:));
sum=pdist2(isec(1,:), isec(idx+1,:), 'cityblock');
%for the rest of the points
for i=2:size(isec,1)-1
others=[isec(1:i-1,:); isec(i+1:end,:)];
[idx,~]=dsearchn(others,isec(i,:));
man=pdist2(isec((i,:), others(idx,:), 'cityblock');
sum=sum+man;
end
%for the last point
[idx,~]=dsearchn(isec(1:end-1,:),isec(end,:));
sum=sum+pdist2(isec(end,:), isec(idx,:), 'cityblock');
avg_dist=sum/size(isec,1);
As dsearch cannot calculate other distances than euclidean, I use it to find the index of the nearest point. After that I have to call the pdist2 function to measure the cityblock distance. What complicates things even more is the fact, that I have to exclude the current point (to which I'm trying to find the closest one); that's the purpos of my 'others' variable and the 2 pieces of code above and below the for-cycle.
To give a bit of context:
The goal is image segmentation. The points are actually line intersections in a grid. I want to calculate the average Manhattan distance in order to use the result as a treshhold to determine which points are roughly in the given row/column (unlike in the case of crosswords, sudokus, nonograms I'm not interested in the square areas between the lines, rather in the intersections).Bálint Udvardyhttps://in.mathworks.com/matlabcentral/profile/authors/9792299-balint-udvardytag:in.mathworks.com,2005:Question/4601482019-05-03T04:00:00Z2020-02-24T21:48:09ZHow can I debug a MEX file on Microsoft Windows Platforms with Microsoft Visual Studio 2017?How can I debug a MEX file with Microsoft® Visual Studio® 2017?
MathWorks Support Teamhttps://in.mathworks.com/matlabcentral/profile/authors/4622813-mathworks-support-teamtag:in.mathworks.com,2005:Question/4807962019-09-17T15:16:16Z2020-02-24T21:31:48ZNot responding on startup, macOS MojaveI have just installed MATLAB 2019b on a Macbook Pro 2019 running macOS Mojave 10.14.6.
Just after installation, Matlab ran fine. However, if I now try to open it I see the splash screen then it freezes on the Matlab window showing no content and I have to force quit. If I run from the command line with -nodesktop it works and I can even load the desktop from there and it works ok. But if I try to load directly it hangs. I doubt it is a conflict as I have installed barely anything else on this macbook yet.William Smithhttps://in.mathworks.com/matlabcentral/profile/authors/3990217-william-smithtag:in.mathworks.com,2005:Question/5073232020-02-24T21:28:58Z2020-02-24T21:28:58ZCan't save figure that contains subplots and a legendI need a figure that uses most of the area for a heatmap, and then has subplots of bar graphs on the side. I am doing this by creating a uipanel for my heatmap, and then a smaller uipanel to hold all of the bar graphs. The following example shows the figure that I want, but when I save it I get the following error:
Error using alternatePrintPath
Dimensions of arrays being concatenated are not consistent.
Error in alternatePrintPath
Error in print (line 83)
pj = alternatePrintPath(pj);
Error in saveas (line 181)
print( h, name, ['-d' dev{i}] )
Error in mre (line 18)
saveas(fig, 'test.png');
The problem has something to do with the legend. Also, if we don't plot the heatmap, the error goes away. Here is the code. I am using R2019b.
fig = figure;
heatmap_panel = uipanel('Position', [0, 0, .7, 1]);
heatmap_data = magic(10);
my_heatmap = heatmap(heatmap_panel, heatmap_data);
bars_panel = uipanel('Position', [.7, 0, .3, 1]);
subplot(2, 1, 1, 'Parent', bars_panel);
bar_data = [.2, .4, .4; .3, .3, .4]';
my_bar = bar(bar_data);
my_legend = legend({'group1', 'group2'});
saveas(fig, 'test.png');
Thomas Keefehttps://in.mathworks.com/matlabcentral/profile/authors/16456421-thomas-keefetag:in.mathworks.com,2005:Question/3628182017-10-23T04:00:00Z2020-02-24T21:28:29ZWhy does creating a standalone application in MATLAB R2017a_Prerelease version generate a warning regarding "startup.m" adding paths?Why does creating a standalone application in MATLAB R2017a_Prerelease version generate a warning regarding "startup.m" adding paths? I get the following warning saying, I may have included folders that may not be present in deployment environment. However, I do not have any such code in my startup.m file.
ERROR: [Warning: Your deployed application may error out because file or folder paths
not present in the deployed environment may be included in your MATLAB startup
file. Use the MATLAB function "isdeployed" in your MATLAB startup file to
determine the appropriate execution environment when including file and folder
paths, and recompile your application.
]
MathWorks Support Teamhttps://in.mathworks.com/matlabcentral/profile/authors/4622813-mathworks-support-teamtag:in.mathworks.com,2005:Question/3635002017-10-26T04:00:00Z2020-02-24T21:26:09ZWhy does mcc generates Warning message about starup file even though the starup file is not present on MATLAB Search Path?I am trying to create standalone application using mcc and getting the Warning message:
[Warning: Your deployed application may error out because file or folder paths
not present in the deployed environment may be included in your MATLAB startup
file. Use the MATLAB function "isdeployed" in your MATLAB startup file to
determine the appropriate execution environment when including file and folder
paths, and recompile your application.
]
I confirmed that there is no starup.m file present on MATLAB search path.
>> which startup.m
'startup.m' not found
>>mcc -m myprogram.m -a ./*.mexw64
MathWorks Support Teamhttps://in.mathworks.com/matlabcentral/profile/authors/4622813-mathworks-support-team