Info
La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.
Constrained Global Optimization Problem with MultiStart, GA and HybridFunction using Parallel Processing whithout Ste
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
David Hastana
el 21 de Feb. de 2020
Cerrada: Rena Berman
el 9 de Oct. de 2020
Hello,
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:
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:
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:
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
1 comentario
Rik
el 22 de Feb. de 2020
I'm not quite sure what should be deleted from your question. Can you try to remove the duplicated text? I'm going to assume the answers you posted can be deleted, as they look like copies of your question body.
Respuesta aceptada
ALAN DENVER
el 22 de Feb. de 2020
Part 2 :
Use Instead
s = serial("COM1");
s.BaudRate = 115200;
fopen(s)
s = serialport("COM1",115200);
See “Transition Your Code to serialport Interface” for more information about using the
recommended functionality.
1-31
R2019b
Mathematics
makima Function: Perform modified Akima cubic Hermite
interpolation
The makima function performs modified Akima cubic Hermite interpolation, similar to the
'makima' interpolation method of griddedInterpolant, interp1, interp2,
interp3, and interpn. The modified Akima cubic Hermite interpolation method has
these properties:
• It is C1 continuous.
• It produces fewer undulations than spline, but the result is not as aggressively
flattened as pchip.
• Unlike pchip, it supports N-D arrays.
• Unlike spline, it does not produce overshoots.
1-32
Graphics
Graphics
Chart Container Class: Develop your own class of charts
Define your own class of charts by creating a subclass of the
matlab.graphics.chartcontainer.ChartContainer base class. If you write scripts
or functions for creating specialized visualizations and share them with others, consider
creating a class implementation. Creating a class enables you to:
• Provide a convenient interface for your users — When users want to customize an
aspect of your chart, they can set a property rather than having to modify and rerun
your graphics code. Users can modify properties at the command line or inspect them
in the Property Inspector.
• Encapsulate algorithms and primitive graphics objects — You implement methods that
perform calculations and manage the underlying graphics objects. Organizing your
code in this way allows you to hide implementation details from users.
The ChartContainer base class supports charts that have a single Cartesian axes. When
you define a chart that derives from this base class, instances of your chart are members
of the graphics object hierarchy. As a result, your charts are compatible with many
aspects of the graphics system. For example, the gca and findobj functions can return
instances of your chart. For more information, see “Chart Development Overview”.
tiledlayout and nexttile Functions: Create configurable layouts
of plots in a figure
Use the tiledlayout and nexttile functions to lay out a tiling of multiple plots within
a figure. The configuration options include:
• Control over the spacing between the plots and around the edges of the layout
• An option for a shared title at the top of the layout
• Options for shared x- and y-axis labels
• An option for displaying a shared axes toolbar
• An option to control whether the tiling has a fixed size or variable size that can reflow
1-33
R2019b
colororder Function: Control the colors in plots
Control the color scheme of your plots by calling the colororder function. When you
change the color scheme using this function, the change has an immediate effect on your
existing plots. If you call the colororder function for an empty figure, the new color
scheme persists in the figure when you call a plotting function.
Bar Charts: Create bar charts with improvements for stacking
and locating the tips of bars
The bar and barh functions have these improvements:
• Stacked groups of bars display negative bars below zero, rather than overlapping the
bars.
• You can locate the tips of bars by getting the values of the XEndPoints and
YEndPoints properties on the Bar object. The locations are useful for adding labels
to the tips of bars.
• Both functions now accept more combinations of scalar, vector, and matrix inputs.
1-34
Graphics
Data Tips: Create and customize data tips
Create data tips on objects with a DataTipTemplate property using the datatip
function. You can create a data tip by specifying the exact coordinates of the data point,
the approximate coordinates of the data point, or the index of the data point within the
plotted data set. Create a data tip between plotted data points by setting the
SnapToDataVertex property to 'off'.
In the Live Editor, generate code for interactively pinned data tips by clicking the Update
Code button. This generated code recreates the data tip the next time you run the live
script.
Customize the content of data tips on additional charts, including Contour, Patch,
Quiver, Bar, and Image objects with a DataTipTemplate property. For more
information, see “Create Custom Data Tips”.
dataTipInteraction Function: Pin data tips at cursor location
Create data tip interactions that pin data tips to the cursor location, rather than the
nearest data point, by setting the SnapToDataVertex property of the data tip interaction
object to 'off':
1-35
R2019b
For more about customizing axes interactions, see “Control Chart Interactivity”.
Axes Toolbar: Save or copy contents of axes as image
To save or copy the contents of a set of axes or a tiled chart layout, hover over the Export
icon
and select an option from the drop-down menu. The available options depend on
the content of the axes.
•
•
•
Save to an image or PDF file by selecting Save As
.
Copy to the clipboard as a PNG image by selecting Copy as Image
.
Copy to the clipboard as a vector graphic for PDFs by selecting Copy as Vector
.
When you create a custom toolbar using the axtoolbar function, include a drop-down
menu with save and copy options by specifying the buttons argument as 'export'.
parallelplot Function: Zoom, pan, and rearrange coordinates
interactively
The parallel coordinates plot has new options for interacting with data:
• Zoom — Use the scroll wheel to zoom.
• Pan — Click and drag the plot to pan.
• Rearrange coordinates — Click and drag a coordinate tick label to move the
corresponding coordinate ruler to a different position.
Property Inspector: Update axis tick values and labels using
clipboard data
You can update the tick values and labels that appear along an axis by copying and
pasting data (for example, from a spreadsheet) into the property inspector. To paste
copied data, open the property inspector and navigate to the ticks property that you want
and select Paste.
to edit. Then, open the drop-down menu by clicking
1-36
Graphics
Image Interpolation: Select an interpolation method for
displaying images
Display images using either nearest neighbor or bilinear interpolation. MATLAB uses
interpolation when it displays a scaled or rotated version of an image.
When you call the image, imagesc, or imshow functions, specify the Interpolation
property name-value pair with either 'nearest' or 'bilinear' as the value. All images
use 'nearest' by default.
For example, this code displays an image using the imagesc function with bilinear
interpolation:
I = imread('peppers.png');
imagesc(I,'Interpolation','bilinear')
legend Function: Create unlimited legend entries and specify
categorical arrays
The legend function has these improvements:
• The legend can display an unlimited number of entries when you specify the subset
argument. In previous releases, legends display up to 50 entries only.
1-37
R2019b
• You can specify label values as categorical arrays in addition to cell arrays and string
arrays.
pcolor Function: Specify categorical, datetime, and duration
data
The pcolor function now accepts categorical, datetime, and duration arrays for X and
Y.
Geographic Plots: Plot data on high-zoom-level basemaps
Plot data on high-zoom-level basemaps hosted by Esri®. For more information about Esri,
see https://www.esri.com. Specify a basemap using the geobasemap function or by
setting the Basemap property of the GeographicAxes or GeographicBubbleChart
object.
'streets-light'
'satellite'
Map designed to
provide geographic
context while
highlighting user
data on a light
background.
Full global basemap
composed of highresolution satellite
imagery.
Hosted by Esri.
1-38
Hosted by Esri.
Graphics
'streets-dark'
'topographic'
Map designed to
provide geographic
context while
highlighting user
data on a dark
background.
General-purpose map
with styling to depict
topographic features.
Hosted by Esri.
Hosted by Esri.
'streets'
General-purpose
road map that
emphasizes accurate,
legible styling of
roads and transit
networks.
Hosted by Esri.
Geographic Plots: Create plots with improved basemap
appearance
Starting in R2018b, basemaps within geographic plots have an improved visual
appearance at noninteger zoom levels. For example, the ZoomLevel property of these
geographic bubble charts is 4.995.
1-39
R2019b
Geographic Axes: Display animations using comet or
animatedline
Display animations on geographic axes using comet or animatedline. For more
information, see “Line Animations”.
Geographic Bubble Charts: Create charts with improved
layout
Geographic bubble charts have an improved visual appearance, including use of figure
space and placement of ticks and tick labels.
When you resize a geographic bubble chart, font sizes and spacing between elements in
the chart automatically adjust to provide the best possible presentation for the new size.
Changing the FontSize property of a geographic bubble chart disables the automatic
resizing of the fonts.
1-40
Graphics
Functionality being removed or changed
Changing ColorOrder or LineStyleOrder on the axes affects existing plots
immediately
Behavior change
If you change the axes ColorOrder or LineStyleOrder properties after plotting into
the axes, the colors and line styles in your plot change immediately. In previous releases,
the new colors and line styles affect only subsequent plots, not the existing plots.
For example, this code plots two lines before changing the value of the ColorOrder
property. In R2019a and previous releases, the colors of the two lines do not change when
you change the ColorOrder property.
plot([0 1],[1 0])
hold on
plot([0 1],[2 0])
ax = gca;
ax.ColorOrder = [1 0 0; 0 1 0];
Starting in R2019b, the lines change immediately to use the new ColorOrder or
LineStyleOrder property values. If you want to prevent the change, set either the axes
LineStyleOrderIndex or ColorOrderIndex property to any value (such as its current
value) before changing the ColorOrder or LineStyleOrder property.
plot([0 1],[1 0])
hold on
plot([0 1],[2 0])
ax = gca;
% Preserve R2019a behavior
ax.ColorOrderIndex = ax.ColorOrderIndex;
ax.ColorOrder = [1 0 0; 0 1 0];
Indexing scheme for ColorOrder and LineStyleOrder might change plot colors
and line styles
Behavior change
In R2019a and previous releases, plots that visualize multiple sets of data rely on an
indexing scheme to select the colors and line styles. The indexing scheme generally works
well, but it does not allow you to change the colors and line styles in a plot after you
create it.
1-41
R2019b
Starting in R2019b, there is a new indexing scheme that enables you to change the colors
and line styles of existing plots. MATLAB always applies this indexing scheme to objects
such as Line, Scatter, and Bar. As a result, your code might produce plots that cycle
through the colors and line styles differently than in previous releases.
One example of the new behavior is when you create a line with a specific color, and then
create another line without specifying a color. In the following code, the first call to the
plot function includes a third argument that specifies the color as red. The second call to
the plot function does not specify a color. In R2019a, the first line is red, and the second
line is blue.
% Plot two lines
hold on
plot([0 1],[1 0],'red')
plot([0 1],[2 0])
If you run the preceding code in R2019b, the first line is red and the second line is
orange. To preserve the original color, set either the axes LineStyleOrderIndex or
ColorOrderIndex property to any value (such as its current value) before plotting into
the axes.
% Preserve R2019a behavior
ax = gca;
ax.ColorOrderIndex = ax.ColorOrderIndex;
% Plot two lines
hold on
plot([0 1],[1 0],'red')
plot([0 1],[2 0])
Predefined colormaps have 256 colors by default
Behavior change
The predefined colormaps, such as parula, jet, and winter, now have 256 colors by
default.
If you have code that depends on a predefined colormap having 64 colors, specify the
number of colors when you set the colormap for the figure, axes, or chart. For example,
colormap(parula(64)) sets the figure's colormap to the 64-color parula colormap.
Alternatively, you can change the default colormap for all figures within your MATLAB
session:
set(groot,'defaultFigureColormap',parula(64))
1-42
Graphics
Pie charts display zero values
Behavior change
When you call the pie or pie3 function and specify data that contains zero values, your
pie chart shows the zero values and corresponding labels. If you call either function with
an output argument, the output includes objects for each zero value.
In previous releases, the functions omit the zero values from the chart and do not return
any objects that correspond to those values. If you do not want to display zero values or
return the corresponding objects, then remove the zeros from your data.
Using the axis function to set axes limits no longer changes the view of the plot
box
Behavior change
When you call the axis function to set limits, the plot box no longer changes its view in
these situations:
• When the plot box is in a 2-D view, and you pass a six-element vector to the axis
function. To preserve the behavior of previous releases, call view(3) after calling the
axis function.
• When the plot box is in a 3-D view, and you pass a four-element vector to the axis
function. To preserve the behavior of previous releases, call view(2) after calling the
axis function.
Default basemap for geographic plots is now 'streets-light'
Behavior change
Starting in R2019b, the default basemap for GeographicAxes and
GeographicBubbleChart objects is 'streets-light'. The 'streets-light'
basemap requires Internet access.
In previous releases, the default basemap was 'darkwater'. This basemap is included
with MATLAB and does not require Internet access.
If you do not have reliable access to the Internet, you can use the 'darkwater' basemap
or download a selection of basemaps onto your local system using the Add-On Explorer.
For more information, see “Access Basemaps in MATLAB”.
Turning on interaction modes disables mouse interactions for geographic bubble
charts
Behavior change
1-43
R2019b
Starting in R2019b, turning on an interaction mode in a figure disables mouse
interactions for geographic bubble charts in the figure. For example, if you turn on zoom
mode using the zoom function, then you can no longer use the mouse to zoom or pan
within the geographic bubble chart. Other interaction modes include pan, rotate, data
cursor, or brush mode.
To zoom or pan within a geographic bubble chart, turn off interaction modes within the
figure and zoom or pan using the built-in mouse interactions.
Geographic bubble charts display tick labels using seconds
Behavior change
Starting in R2019b, the tick label format for geographic bubble charts is degrees,
minutes, and decimal seconds (DMS) rather than degrees and decimal minutes (DM).
1-44
App Building
App Building
uistyle Function: Create styles for rows, columns, or cells in a
table UI component
You can create different styles for specific rows, columns, or cells in a table UI component
using the uistyle and addStyle functions. For example, you can make the cells in a
specific column red with italic font. To retrieve styles that have been applied, get the
StyleConfigurations property of the Table object. To remove a style from a table UI
component, use the removeStyle function.
Cell styles in table UI components are supported only in App Designer apps and in figures
created with the uifigure function.
uigridlayout Function: Configure grid rows and columns to
adjust automatically to fit components
Grid layouts can automatically adjust to the minimum size needed to fit the components
that are in it. To configure grid rows and columns to fit components dynamically, specify
'fit' as the value of the RowHeight or ColumnWidth properties for specific rows and
columns in the GridLayout object. For example, setting 'RowHeight' to
{'fit',50,'1x'} specifies that the height of the first row is tightly fit around the
components, the second row is fixed at 50 pixels, and the third row uses the remaining
vertical space.
This feature is especially useful when you are creating rows and columns of text-based
components because when you use 'fit', you don't have to know how tall or wide to
make the rows and columns of the grid layout manager. The 'fit' option for row height
and column width is also useful if your app is translated to another language or runs on
different platforms.
The uigridlayout function is supported only in App Designer apps and in figures
created with the uifigure function.
uitable Function: Sort table UI components interactively when
using logical, numeric, string, or cell arrays
You can interactively sort table UI components when the Data property contains logical
data, numeric data, string data, or cell array data. To sort table UI components that
1-45
R2019b
contain these data types, set the ColumnSortable property of the Table object. To
update visualizations based on how a table UI component was sorted, also use the
DisplayData property and a DisplayDataChangedFcn callback function.
Sortable columns in table UI components are supported only in App Designer apps and in
figures created with the uifigure function.
uihtml Function: Embed HTML, JavaScript, or CSS content in
apps and on the App Designer canvas
To embed HTML, JavaScript®, or CSS in your app, call the uihtml function or, in App
Designer, drag an HTML UI component from the Component Library onto the canvas.
HTML UI components are supported only in App Designer apps and in figures created
with the uifigure function.
App Designer: Convert components in a UI figure or container
from pixel-based positioning to a grid layout manager
You can convert the children of a UI figure or container from pixel-based positioning to
being positioned by a grid layout manager. To use a grid layout manager where you were
previously using pixel-based positioning, drag a grid layout from the Component Library
onto the canvas or into an existing container component, like a panel. Alternatively, rightclick the canvas or container component and select Apply Grid Layout.
The grid layout manager automatically creates rows and columns to accommodate the
components, and preserves their approximate positions. When you add a grid layout, the
component hierarchy updates in the Component Browser.
App Designer: Convert an existing app into an auto-reflowing
app
To convert an existing app into an auto-reflowing app, expand the Convert
dropdown menu in the Canvas tab, and select 2-Panel App with Auto-Reflow or 3-Panel
App with Auto-Reflow.
Auto-reflowing apps automatically resize and reflow content based on screen size, screen
orientation, and platform. Use apps with auto-reflow if you expect to run or share your
1-46
App Building
apps across multiple environments or desktop resolutions. For more details, see “Apps
with Auto-Reflow”.
App Designer: Suppress Code Analyzer warning messages
In the App Designer Code View editor, you can suppress Code Analyzer warnings for a
single line or for the entire app file. To suppress warnings, right-click a warning and, from
the context menu, select:
• Suppress Message... > On This Line
• Suppress Message... > In This File
For example,
Error messages, however, cannot be suppressed.
App Designer: Open App Designer from the MATLAB toolstrip
To open App Designer from the MATLAB toolstrip, click the Design App
Apps tab.
button in the
App Testing Framework: Perform gestures on polar axes and
UI images
The App testing framework supports gestures on more UI components.
• Perform hover and press gestures in tests on polar axes.
• Perform press gestures in tests on UI images.
1-47
R2019b
For example, perform interactive gestures on PolarAxes object pax and Image object
im.
fig = uifigure;
pax = polaraxes(fig,'ThetaAxisUnits','radians');
im = uiimage(fig,'ImageSource','membrane.png','Position',[10 10 100 100]);
testCase = matlab.uitest.TestCase.forInteractiveUse;
testCase.hover(pax);
testCase.press(pax,[pi/2 0.5]);
testCase.press(im);
For more information, see the hover and press reference pages.
Functionality being removed or changed
GUIDE will be removed in a future release
Still runs
The GUIDE environment and the guide function will be removed in a future release.
After GUIDE is removed, existing GUIDE apps will continue to run in MATLAB but will not
be editable using the drag-and-drop environment in GUIDE. To continue editing an
existing GUIDE app and help maintain its compatibility with future MATLAB releases, use
one of the suggested migration strategies listed in the table.
App Development
Migration Strategy
How to Migrate
Frequent or ongoing
development
Migrate your app to App
Designer
Use the GUIDE to App
Designer Migration Tool for
MATLAB on
mathworks.com
Minimal or occasional
editing
Export your app to a single Open the app in GUIDE and
MATLAB file to manage your select File > Export to
app layout and code using
MATLAB-file
MATLAB functions
0 comentarios
Más respuestas (6)
M
el 21 de Feb. de 2020
Update your code like this:
A=rand(2,2);
B=[1 ;0];
n = length (A);
Com = B;
for x = 1: n-1
Com = [Com, (A ^ (x)) * B];
end
You can then chek the resuts with:
isequal(Com,ctrb(A,B))
ans =
logical
1
13 comentarios
Walter Roberson
el 21 de Feb. de 2020
http://www.mathworks.com/matlabcentral/answers is the direct link to the list of current questions and so on, skipping the "landing page".
Walter Roberson
el 21 de Feb. de 2020
We have had too many people trying to delete questions after they get an answer, so we rarely delete questions that have a valid solution attempt. The regular volunteers tend to feel that their generosity has been taken advantage of when answered questions are deleted.
I will report the performance issue to the appropriate people, but it is unlikely that we would delete the questions to solve a performance issue.
ALAN DENVER
el 22 de Feb. de 2020
It could help you :
Part 1 :
R2019b
For more information, see VideoReader.
VideoReader Object: Improved performance in generated
code with row-major layout
For large video files, the generated code for the VideoReader object with a row-major
layout option shows improved performance. For example, the timingTest function
shows about a 4x speed-up on a H.264 video file with a resolution of 1280x720.
function [t, data] = timingTest(fileName)
vidObj = VideoReader(fileName);
data = cell(20,1);
tic;
for cnt = 1:20
data{cnt} = readFrame(vidObj);
end
t = toc;
end
Generate code for the timingTest function with the row-major flag. The codegen
command creates a function timingTest_mex with the C and C++ generated code.
codegen timingTest -args {coder.typeof('', [1 inf])} -rowmajor
For a H.264 video file with a resolution of 1280x720, the execution times are:
R2019a: 4.04s
R2019b: 0.95s
The code was timed on a Windows 10, Intel® Xeon® CPU W-2133 @ 3.6 GHz test system
by calling the function timingTest_mex. The higher the video file resolution (measured
by frame size), the greater the performance improvement becomes.
Import Tool: Generate simpler code when importing from
fixed-width text files
Import Tool now operates consistently across different platforms and generates code
that is easy to read when importing fixed-width text files. For example, the generated
code contains readtable and FixedWidthImportOptions, which makes the code
1-24
Data Import and Export
simpler to read and use. For more information, see “Read Text File Data Using Import
Tool”.
save Function: Save workspace variables to a MAT-file version
7 without compression
Previously, the save command, when saving workspace variables to a version 7 MAT-file,
used compression as the default (and the only) option. Now, save supports the 'nocompression' option for MAT-file version 7.
By default, saving a variable myVariable compresses the data and saves it to a version 7
MAT-file. The -v7 flag is optional.
save myFile.mat myVariable –v7
To save myVariable without compression, use:
save myFile.mat myVariable –v7 –nocompression
For more information, see save.
xmlread Function: Prevent reading of XML files that contain
DOCTYPE declarations
You can prevent reading XML files that contain DOCTYPE declarations by setting the
'AllowDoctype' name-value pair to false. For more information, see the xmlread
reference page.
imread function: Supports reading specified images from
PGM, PBM, or PPM file formats
The imread function supports reading specified images from multi-image PGM, PBM, or
PPM file formats. For more information, see the imread reference page.
Scientific File Format Libraries: CFITSIO Library upgraded to
version 3.450
The CFITSIO library is upgraded to version 3.450.
1-25
R2019b
Scientific File Format Libraries: LibTIFF Library upgraded to
version 4.0.10
The LibTIFF library is upgraded to version 4.0.10.
RESTful Functions: Support for authentication
The RESTful web services functions webread, websave, and webwrite also support
Digest authentication. For more information, see the weboptions 'Username'
argument.
For the list of supported authentications for RESTful functions, see “Server
Authentication”.
Compatibility Considerations
The RESTful functions webread, webwrite, and websave now adhere more closely to
the Internet Engineering Task Force (IETF®) document RFC 7617 for Basic
authentication. As a result, MATLAB might error when a RESTful function communicates
with a server that proactively expects Basic authentication but does not return a 401
challenge response.
To update your code, see How do I preemptively include a Basic Authentication header
when working with "webread"/"webwrite"/"websave" in MATLAB R2019b?
tcpclient, read, and write Functions: Generate C and C++
code
The tcpclient, read, and write functions support C and C++ code generation using
MATLAB Coder.
Bluetooth Low Energy Interface: Support for scanning and
interacting with peripheral devices
You can use MATLAB commands to perform the following operations:
• Scan for nearby peripheral devices and view advertising data using the blelist
function
1-26
Data Import and Export
• Connect to peripheral devices using the ble function
• Access device characteristics and descriptors using the characteristic and
descriptor functions
• Read device characteristic data and descriptor data using the read function
• Write to device characteristics and descriptors using the write function
• Enable and disable notification or indication for a characteristic using the subscribe
and unsubscribe functions
For more information, see “Bluetooth Low Energy Communication”.
Serial Port Devices: New functions and properties
The serial port interface has a new set of functions and properties. The existing
functionality still runs, but new function names and properties are recommended. The
new interface has improved performance.
Get started with the new interface by viewing a list of all serial ports on your computer
using serialportlist.
list = serialportlist
list =
1×4 string array
"COM1"
"COM3"
"COM4"
"COM8"
Then, create a serialport object, write data to the device, and read from it.
s = serialport("COM8",115200);
write(s,1:5,"uint32")
read(s,5,"uint32");
For more information, see “Serial Port Devices”.
Compatibility Considerations
For more information about updating your code to use the recommended functionality,
see “Transition Your Code to serialport Interface”.
1-27
R2019b
Functionality being removed or changed
Import Tool does not support importing text data as cell array of character
vectors
Behavior change
Previously, Import Tool provided an option to import text data as a cell array of
character vectors. Starting in R2019b, Import Tool does not support this. Instead, the
Import Tool app imports text data as string arrays.
To preserve the previous behavior, convert the imported text data to a cell array of
character vectors using the cellstr function.
UseExcel parameter for spreadsheets
Behavior change
The default setting for UseExcel on Windows systems with Excel® installed is false.
The UseExcel parameter appears on these spreadsheet functions: readtable,
readtimetable, readmatrix, readcell, readvars, writetable, writetimetable,
writematrix, and writecell.
To preserve the previous behavior, update calls to these functions to specify the
UseExcel parameter as true. For example, for the readtable function, update your
code as follows.
T = readtable(filename,'UseExcel',true)
xlsfinfo function is not recommended
Still runs
The xlsfinfo function is not recommended. Use the function sheetnames instead.
There are no plans to remove xlsfinfo at this time. The sheetnames function has these
advantages over the xlsfinfo function:
• Support for sheet names containing non-ASCII characters
• Better cross-platform support and performance
• Ability to work with remotely stored data
This table shows a typical use of xlsfinfo and how to update your code to use
sheetnames.
1-28
Data Import and Export
Not Recommended
Recommended
[~,sheets] = xlsfinfo('myData.xls') sheets = sheetnames('myData.xls')
NumberOfFrames property of the VideoReader object is not recommended
Still runs
The NumberOfFrames property of the VideoReader object is not recommended. Use the
property NumFrames instead. Update all instances of NumberOfFrames with NumFrames.
There are no plans to remove the NumberOfFrames parameter at this time.
Array of VideoReader objects is not supported
Creating an array of VideoReader objects is not supported. Update your code to remove
arrays of VideoReader objects. For example, the following code returns an error.
v = VideoReader('xylophone.mp4');
v(end+1) = VideoReader('xylophone.mpg');
Array formation and parentheses-style indexing
with objects of class 'VideoReader' is not allowed.
Use objects of class 'VideoReader' only as scalars
or use a cell array.
Tiff object for writing certain TIFF files
Writing TIFF images with certain combinations of photometric configuration and the
number of samples per pixel is not recommended. The value of SamplesPerPixel must
be equal to the sum of Photometric color channels and the ExtraSamples specified in
the Tiff object. For more information, see Tiff and write.
imwrite function does not support writing of indexed PNG files that have
insufficient colormap entries
Starting in R2019b, for writing indexed PNG files, you must specify a colormap with
enough entries to interpret the image correctly. For more information, see the imwrite
reference page.
imfinfo function returns information on multiple images from PGM, PBM, and
PPM files
Behavior change
1-29
R2019b
Previously, for the PGM, PBM, and PPM file formats, the imfinfo function returned a
single 1-by-1 structure. The structure contained information about only the first image,
even if the file contained multiple images in it.
Starting in R2019b, if the PGM, PBM, and PPM files have multiple images, then imfinfo
returns a structure array containing information on multiple images in the file. For
instance, for a PGM file containing M images, imfinfo returns a 1-by-M structure array
containing information corresponding to all the images in the file.
This table shows how to update your code to get the Height (or any other property) of
the first image of a multi-image PBM, PGM, or PPM file.
Not Recommended
info = imfinfo('MultiImgFile.pgm')
info.Height
Recommended
info = imfinfo('MultiImgFile.pgm')
info(1).Height
For more information, see imfinfo.
web Function
Behavior change
The web function now opens external sites using your system browser by default.
Previously, the web function opened external sites using the MATLAB browser. Using the
system browser is recommended when opening external sites.
To use the MATLAB browser as the default browser for external sites, go to the Home
tab, and in the Environment section, click Preferences. Select MATLAB > Web and in
the System Web browser section, clear the Use system web browser when opening
links to external sites (recommended) option.
Web services use system certificates
Behavior change
The default value for the CertificateFilename option in the weboptions function
and the matlab.net.http.HTTPOptions.CertificateFilename property is 'default'. If the
value is 'default', then MATLAB uses system certificates.
Previously by default, MATLAB used the PEM certificate file that ships with MATLAB.
seriallist function is not recommended
Still runs
1-30
Data Import and Export
seriallist is not recommended. Use serialportlist instead. See “Transition Your
Code to serialport Interface” for more information about using the recommended
functionality.
serial function is not recommended
Still runs
serial and its object properties are not recommended. Use serialport and its
properties instead.
This example shows how to connect to a serial port device using the recommended
functionality.
Functionality
0 comentarios
ALAN DENVER
el 22 de Feb. de 2020
Part 3 :
App Designer is the recommended app development environment in MATLAB. To create
new apps, use “App Designer” and the appdesigner function instead.
To learn more about migrating apps, see “GUIDE Migration Strategies”.
For more information about App Designer, go to Comparing GUIDE and App Designer on
mathworks.com.
1-48
App Building
javacomponent function and JavaFrame property will be removed in a future
release
Warns
The javacomponent function and the JavaFrame figure property are undocumented
and will be removed in a future release. Update your code to use documented
alternatives. For a list of documented functionality that you can use instead, see
Recommendations for Java and ActiveX Users on mathworks.com.
actxcontrol, actxcontrollist, and actxcontrolselect functions will be removed in a
future release
Warns
The actxcontrol, actxcontrollist, and actxcontrolselect functions will be
removed in a future release. Update your code to use alternate functionality. For a list of
functionality that you can use instead, see Recommendations for Java and ActiveX Users
on mathworks.com.
Support for running deployed web apps in Internet Explorer has been removed
Errors
Support for running deployed web apps in Internet Explorer® has been removed. Use the
current versions of Google Chrome™ (recommended), Safari, Firefox®, or Microsoft
Edge® to run deployed web apps instead.
For more information on supported web app browsers, see “Supported Browsers and
Platform Incompatibilities” (MATLAB Compiler).
Text alignment and font size have changed in table column and row headers
Behavior change
Starting in R2019b, table UI components created in App Designer or in figures created
with the uifigure function have a different visual appearance when they contain certain
kinds of data. Column and row headers of table UI components that contain numeric,
logical, string, or cell array data have these visual differences compared to previous
releases:
• Smaller font size
• Column headers are left-aligned instead of center-aligned
• Row headers are center-aligned instead of left-aligned
1-49
R2019b
For example, this code that creates a table UI component with mixed cell array data
renders differently in R2019b than it does in R2019a.
fig = uifigure;
d = {'Male',52,true;'Male',40,true;'Female',25,false};
uit = uitable(fig,'Data',d);
uit.ColumnName = {'Gender','Age','Authorized'};
Starting in R2019a, the same visual differences apply to column and row headers in table
UI components that contain table array data. For example, this code that uses a table
array to display datetime values in a table UI component renders differently in R2019a
than it does in R2018b.
fig = uifigure;
dates = datetime([2016,01,17; 2017,01,20],'Format','MM/dd/uuuu');
m = [10; 9];
tdata = table(dates,m,'VariableNames',{'Date','Measurement'});
uit = uitable(fig,'Data',tdata);
uit.RowName = 'numbered';
1-50
Performance
Performance
table Data Type Indexing: Improved performance when
assigning elements by subscripting into large table variables
table subscripted assignment into large table variables is significantly faster.
Performance is now essentially constant with the number of elements in each table
variable.
• For example, when you use dot indexing to assign elements to a variable with 106
elements, performance in R2019b is approximately 40x times faster, as shown below.
function timingTest()
t = table(zeros(1e6,1));
indices = randi(1e6,1,10000);
tic;
for i = indices
t.Var1(i) = rand;
end
toc
end
The approximate execution times are:
R2019a: 47.83 s
R2019b: 1.20 s
• Similarly, assignment using curly braces is faster. For example, when you assign into
three table variables with 106 elements, performance in R2019b is approximately 18x
faster.
function timingTest()
t = table(zeros(1e6,1), ones(1e6,1), nan(1e6,1));
indices = randi(1e6,1,10000);
tic;
for i = indices
t{i,:} = rand;
end
toc
end
1-51
R2019b
The approximate execution times are:
R2019a: 156.39 s
R2019b: 8.51 s
The code was timed on a Windows 10 system with a 3.6 GHz Intel Xeon W-2133 CPU by
calling each version of the timingTest function.
The larger the table variables are, the greater the performance improvement becomes.
However, the performance improvement occurs only when you make table subscripted
assignments within a function. There is no improvement when subscripting into tables at
the command line, or within try-catch blocks.
datetime, duration, and calendarDuration Data Type Indexing:
Improved performance when assigning elements by
subscripting into large arrays
datetime, duration, and calendarDuration subscripted assignment into large
arrays is significantly faster. Performance is now essentially constant with the number of
elements in an array.
• For example, when you assign into a datetime array with 106 elements, performance
in R2019b is approximately 106x times faster, as shown below.
function timingTest()
dt = datetime + hours(1:1e6);
indices = randi(1e6,1,10000);
rhs = NaT;
tic;
for i = indices
dt(i) = rhs;
end
toc
end
The approximate execution times are:
R2019a: 49.00 s
R2019b: 0.46 s
1-52
Performance
• Similarly, assignment into a duration array is faster. For example, when you assign
into a duration array with 106 elements, performance in R2019b is approximately
106x times faster.
function timingTest()
d = hours(1:1e6);
indices = randi(1e6,1,10000);
tic;
for i = indices
d(i) = NaN;
end
toc
end
The approximate execution times are:
R2019a: 48.66 s
R2019b: 0.46 s
The code was timed on a Windows 10 system with a 3.6 GHz Intel Xeon W-2133 CPU by
calling each version of the timingTest function.
The larger the arrays are, the greater the performance improvement becomes. However,
the performance improvement occurs only when you make subscripted assignments
within a function. There is no improvement when subscripting into datetime, duration,
and calendarDuration arrays at the command line, or within try-catch blocks.
datetime Data Type Indexing: Improved performance when
referring or assigning to date and time components of
datetime arrays
Subscripted references and assignments to components of datetime arrays is
significantly faster.
• For example, when you refer to a component of a datetime array with 104 elements,
performance in R2019b is approximately 25x times faster, as shown below.
function timingTest()
dt = datetime + hours(1:1e4);
indices = randi(1e4,1,10000);
1-53
R2019b
tic;
for i = indices
x = dt.Hour(i);
end
toc
end
The approximate execution times are:
R2019a: 12.97 s
R2019b: 0.52 s
• Similarly, assignment into a component of a datetime array is faster. For example,
when you assign into a component of a datetime array with 104 elements,
performance in R2019b is approximately 32x times faster.
function timingTest()
dt = datetime + days(1:1e4);
indices = randi(1e4,1,10000);
tic;
for i = indices
dt.Hour(i) = 0;
end
toc
end
The approximate execution times are:
R2019a: 22.51 s
R2019b: 0.70 s
The code was timed on a Windows 10 system with a 3.6 GHz Intel Xeon W-2133 CPU by
calling each version of the timingTest function.
The larger the arrays are, the greater the performance improvement becomes. However,
the performance improvement occurs only when you make subscripted assignments
within a function. There is no improvement when subscripting into datetime arrays at
the command line, or within try-catch blocks.
1-54
Performance
uitable Function: Faster performance when data type is
numeric, logical, or a cell array of character vectors
Tables created with the uitable function have better rendering performance, and higher
frame rates while scrolling when they contain certain kinds of data. The improvements
occur when the Data property contains numeric data, logical data, or a cell array of
character vectors. The table must be parented to a figure created with the uifigure
function, or one of its child containers.
Tables containing these data types render up to 40% faster, and interaction performance
(like scrolling) is up to 75% faster. For example, on a test system, this code that uses
numeric data renders the table faster in R2019b than in previous releases.
rows = 10000;
columns = 25;
ndata = randi(30,[rows columns]);
fig = uifigure;
uit = uitable(fig,'Data',ndata);
unzip and gunzip Functions: Improved performance when
extracting contents of zip files and GNU zip files
Extracting the contents of zip files and GNU zip files using unzip and gunzip is
significantly faster when extracting files on network drives.
• For example, when you extract the contents of the example zip file myarchive.zip
with a file size of 53 MB on a network drive, performance in R2019b is approximately
1.5x faster, as shown below.
function timingTest()
unzip myarchive.zip;
end
The approximate execution times are:
R2019a: 3.06 s
R2019b: 2.03 s
• Similarly, when you extract the contents of the example GNU zip file
myotherarchive.gz with a file size of 27 MB on a network drive, performance in
R2019b is approximately 2x faster, as shown below.
1-55
R2019b
function timingTest()
gunzip myotherarchive.gz;
end
The approximate execution times are:
R2019a: 37.22 s
R2019b: 18.22 s
The code was timed on a Windows 10 test system with a 3.6 GHz Intel Xeon CPU E5-1650
CPU across a Gigabit Ethernet connection using the timeit function:
timeit(@timingTest)
Results vary depending on several factors, including connection speed and whether the
network files are cached on the system.
1-56
Software Development Tools
Software Development Tools
Unit Testing Framework: Run tests in parallel with your
custom plugins
You can now run unit tests in parallel when you extend the TestRunner instance with
your custom plugins. For more information, see Run Tests in Parallel with Custom Plugin.
Unit Testing Framework: Validate count in string constraints
The ContainsSubstring, IsSubstringOf, and Matches constraints can now count a
string scalar or character vector for a given number of times. To specify the number of
occurrences, use the 'WithCount' parameter. For example:
import matlab.unittest.constraints.*
testCase = matlab.unittest.TestCase.forInteractiveUse;
testCase.verifyThat('This is long',ContainsSubstring('is','WithCount',2))
Verification passed.
testCase.verifyThat('Gain Main Rain',Matches('[GMR]ain','WithCount',2))
Verification failed.
--------------------Framework Diagnostic:
--------------------Matches failed.
--> Actual count does not match expected count.
Actual Count:
3
Expected Count:
2
Actual char:
Gain Main Rain
Regular Expression:
[GMR]ain
1-57
R2019b
Performance Testing Framework: Visually compare two
TimeResult arrays
The matlab.perftest.TimeResult class has a new method comparisonPlot, which
enables you to visually compare the time measurement results of two equal-sized sets of
performance tests.
App Testing Framework: Perform gestures on polar axes and
images
The app testing framework supports gestures on more UI components.
• Perform hover and press gestures in tests on polar axes.
• Perform press gestures in tests on images.
Projects: Delete project definition files
You can now use matlab.project.deleteProject to easily stop managing your folder
with a project and delete all related project definition files without affecting the
remaining files.
Compare Git Branches: Show differences and save copies
In a project under Git™ source control, you can now select any two revisions and examine
file differences. You can show differences between two development branches and save a
copy of the selected file on either branch. See “Compare Branches”.
Functionality being removed or changed
Character vectors are no longer equivalent to enumerations in qualifications
Behavior change
Starting in R2019b, actual and expected values in qualifications must have the same type
when the expected value is an enumeration of a handle class. For example, consider this
enumeration class:
classdef MyClass < handle
enumeration
X
Y
1-58
Software Development Tools
end
end
The following test fails because 'X' does not represent the enumeration MyClass.X:
testCase = matlab.unittest.TestCase.forInteractiveUse;
testCase.verifySameHandle('X',MyClass.X)
Verification failed.
--------------------Framework Diagnostic:
--------------------verifySameHandle failed.
--> Values do not refer to the same handle.
--> Value must be a handle object. It is of class "char".
--> Classes do not match.
Actual Value class
: [char]
Expected Handle Object class : [MyClass]
Actual char:
X
Expected Handle Object:
MyClass enumeration
X
In previous releases, the test passed because MATLAB treated 'X' as a representation of
the expected enumeration. This change of behavior affects tests using the
IsSameHandleAs constraint class or the following qualification methods:
verifySameHandle, assumeSameHandle, assertSameHandle,
fatalAssertSameHandle, verifyNotSameHandle, assumeNotSameHandle,
assertNotSameHandle, and fatalAssertNotSameHandle.
1-59
R2019b
External Language Interfaces
C++ Interface: Options for publishing C++ interface library
MATLAB automatically renames classes, functions, enumerations, and member functions
with C++ names that are invalid in MATLAB using the matlab.lang.makeValidName
function. For example, MATLAB converts the class name _myclass in library mylib to
x_myclass. As of R2019b, you can modify x_myclass in the library definition file. For
example, you can change the name to myclass. When you use the class in MATLAB, type
clib.mylib.myclass. Renaming C++ namespaces or the MATLAB package is not
supported.
To specify the shape for object pointer types as scalar for all functions in a library, use the
name-value pair argument 'TreatObjectPointerAsScalar' when building the library.
To specify the shape for const char * pointer types as scalar for all functions, use the
'TreatConstCharPointerAsCString' argument.
To provide a list of macro definitions, use the name-value pair argument DefinedMacros
when building the library. To provide a list of macro cancellations, use the
UndefinedMacros argument.
For more information, see clibgen.generateLibraryDefinition and
clibgen.buildInterface.
C++ Interface: nullptr supported as output argument
As of R2019b, the “C++ interface returns type-specific empty values for nullptr” on page
1-63. To test for fundamental nullptr types, call the isempty function. To test for
nullptr objects, call the clibIsNull function.
C++ Interface: Read-only (const) object support
As of R2019b, the “C++ interface treats read-only objects like C++” on page 1-63. To
determine if a C++ object is read-only, call the clibIsReadOnly function.
Java Interface: JRE version 1.8.0_202 support
The MATLAB interface to Java supports JRE™ version 1.8.0_202, providing improved
security and access to new Java features.
1-60
External Language Interfaces
Out-of-Process Execution of C++ MEX Functions: Customize
environment variables
To customize the environment of a MEX host process that you use to execute a MEX
function, call mexhost with the "EnvironmentVariables" argument.
HTTP Web Services: Server authentication support for NTLM
and Kerberos protocols
The HTTP interface also supports these protocols for server authentication.
• Windows — NTLM and Kerberos
• Linux® and macOS — NTLM
For more information, see “Server Authentication”.
HTTP Web Services: Timeout options
MATLAB has new timeout options for transmitting messages using the HTTP interface.
• DataTimeout — timeout in seconds between packets on the network
• KeepAliveTimeout — how long the connection to the server stays open after an initial
connect, enabling multiple successive messages to be sent over the same connection
• ResponseTimeout — seconds to wait for the header of the response from the server
after sending the last packet of a request
For more information, see matlab.net.http.HTTPOptions.
Python Interface: Execute Python functions out of process
Run Python® functions in processes that are separate from the MATLAB process. For
more information, see “Out-of-Process Execution of Python Functionality”. Use this mode
to call functions in third-party libraries that are not compatible with MATLAB.
Python Interface and Engine: Version 3.5 support
discontinued
Support for Python version 3.5 is discontinued.
1-61
R2019b
Compatibility Considerations
To ensure continued support for your applications, upgrade to a supported version of
Python, version 3.6 or 3.7.
Perl 5.30.1: MATLAB support
As of R2019b Update 3, MATLAB ships with Perl version 5.30.1.
• See www.perl.org for a standard distribution of perl, perl source, and information
about using perl.
• See https://metacpan.org/pod/HTML::Parser for a standard distribution of
HTML::Parser, source code, and information about using HTML::Parser.
• See https://metacpan.org/pod/HTML::Tagset for a standard distribution of
HTML:Tagset, source code, and information about using HTML:Tagset.
Compatibility Considerations
If you use the perl command on Windows platforms, see www.perl.org for information
about using this version of the Perl programming language.
Compiler support changed for building MEX files and
standalone MATLAB engine and MAT-file applications
Support
Compiler
Platform
®
Added
Microsoft Visual Studio 2019 for C and C++
Windows
Discontinued
Intel Parallel Studio XE 2015 and XE 2016 for
Fortran
Windows
macOS
To ensure continued support for building your MEX files, consider upgrading to another
supported compiler. For an up-to-date list of supported compilers, see the Supported and
Compatible Compilers website.
1-62
0 comentarios
ALAN DENVER
el 22 de Feb. de 2020
Part 4 :
External Language Interfaces
Functionality being removed or changed
C++ interface treats read-only objects like C++
Behavior change
A C++ read-only object is an object declared with the C++ const attribute. You might
get such an object as the output of a function or as a data member of a class. Starting in
R2019b, the C++ interface for MATLAB honors the const type qualifier ensuring that the
MATLAB behavior matches the C++ behavior of const-qualified types. MATLAB throws
an error if you use a read-only object as follows:
• Passing the object to functions with non-const inputs
• Calling a non-const method on the object
• Modifying object properties
To test if an object is read-only, call the clibIsReadOnly function.
In R2019a, the interface ignores the const type qualifier, allowing the MATLAB user to
utilize const objects incorrectly.
C++ interface returns type-specific empty values for nullptr
Behavior change
Starting in R2019b, the C++ interface returns type-specific empty values for functions
that return nullptr. For more information about nullptr return types. see “MATLAB to
C++ Data Type Mapping”.
• For type double, MATLAB continues to return [] for the value double.empty.
• For all other fundamental types, MATLAB returns an MLTYPE.empty value. To test for
nullptr types, call the isempty function.
• For nonfundamental types, MATLAB returns a nullptr object. To test for nullptr
objects, call the clibIsNull function.
In R2019a, for fundamental and nonfundamental types, the interface returns a
double.empty ([]) value.
For example, suppose that these C++ functions return nullptr:
class A {
public:
double val;
1-63
R2019b
};
// Function returning nullptr object
A* returnNullptrObject() {
return nullptr;
}
// Functions returning nullptr primitive type ptr
double* returnDoubleNullptr () {
return nullptr;
}
const char* returnStringNullptr () {
return nullptr;
}
R2019a
R2019b
For objects, MATLAB returns []
(double.empty).
MATLAB returns nullPtr for an object of
class A.
nullReturn = clib.nullptr.returnNullptrObject
nullReturn = clib.nullptr.returnNullptrObject
nullReturn =
[]
nullReturn =
null A
For fundamental types, MATLAB returns MATLAB returns empty string array for type
[].
const char*.
nullReturn = clib.nullptr.returnStringNullptr
nullReturn = clib.nullptr.returnStringNullptr
nullReturn =
[]
nullReturn =
0×0 empty string array
For type double, MATLAB returns [].
No change. MATLAB returns [].
nullReturn = clib.nullptr.returnDoubleNullptr
nullReturn = clib.nullptr.returnDoubleNullptr
nullReturn =
[]
nullReturn =
[]
pyversion is not recommended
Still runs
pyversion is not recommended. Use pyenv instead. There are no plans to remove
pyversion at this time.
1-64
External Language Interfaces
To execute Python functions out of process, MATLAB provides a new function, pyenv.
This function configures Python environment settings, including the version. Even if you
do not use the out-of-process feature, MathWorks recommends using pyenv for managing
Python settings. For more information, see “Out-of-Process Execution of Python
Functionality”.
C MEX and engine applications: true, false, and bool defined by <stdbool.h>
Behavior change
The definition for true, false, and bool has changed for building MEX files and
standalone MATLAB engine and MAT-file applications with C99 compatible compilers on
Windows and Linux platforms. MATLAB defines these values using <stdbool.h> as
defined by IEEE Std 1003.1:
The <stdbool.h> header shall define
bool
Expands to _Bool.
true
Expands to the integer constant
false
Expands to the integer constant
_bool_true_false_are_defined
Expands to the integer constant
the following macros:
1.
0.
1.
In R2019a and earlier, MATLAB defined these values on Windows and Linux platforms as:
• true — #defined as 1
• false — #defined as 0
• bool — typedef as unsigned char
For Apple macOS platforms, there is no change.
actxcontrol, actxcontrollist, and actxcontrolselect functions will be removed in a
future release
Warns
The actxcontrol, actxcontrollist, and actxcontrolselect functions will be
removed in a future release. MATLAB will support COM server objects only.
1-65
2
R2019a
Version: 9.6
New Features
Bug Fixes
Compatibility Considerations
R2019a
Environment
Live Editor Controls: Add check boxes, edit fields, and buttons
to set variable values and run the live script
You can add check boxes and edit fields to your live scripts to interactively set variable
values. You also can add a button to run the live script when clicked.
To add a check box, edit field, or button, go to the Live Editor tab, click
Control ,
and select from the available controls. For more information, see Add Interactive Controls
to a Live Script.
Live Editor Controls: Specify what code to run when a control
value changes
By default, when you change the value of an interactive control, the Live Editor runs the
section that contains the control. You can now configure an interactive control to run all
sections, run the current section and all remaining sections, or to do nothing.
To configure the control, right-click the control and select Configure Control. Then, in
the Execution section, select from the available options.
Configuring an interactive control to do nothing when changed is useful when your live
script contains multiple interactive controls and you only want to run the code after
changing all of their values. Add a button to the live script to run the code when clicked.
Live Editor Controls: Hide code when sharing and exporting
live scripts with interactive controls
You can hide the code in a live script, showing only the interactive controls, output, and
formatted text. Hiding the code is useful when sharing and exporting live scripts.
To hide the code in a live script, click the hide code
script. To show the code again, click the output inline
button.
2-2
button to the right of the live
button or the output on right
Environment
If you export the live script to PDF, HTML, LaTeX, or Microsoft Word, the code remains
hidden.
Live Editor Export: Save live scripts and functions as
Microsoft Word documents
To create editable, static documents capable of being viewed outside of MATLAB, save
live scripts and functions as Microsoft Word documents. To save a live script or function
as a Microsoft Word document, on the Live Editor tab, select Save > Export to Word.
This format is only available on Windows platforms.
For more information about sharing live scripts and functions, see Share Live Scripts and
Functions.
Live Editor Output: Enable animations in plots to show
changes in data over time
You can enable for-loop animations in the Live Editor to show changes in plotted data
over time.
To enable animations in the Live Editor, set the
matlab.editor.AllowFigureAnimations setting to true:
s = settings;
s.matlab.editor.AllowFigureAnimation.PersonalValue = true;
Note Enabling animations disables support for uicontrols in the Live Editor.
For example, this code turns on animations in the Live Editor, and then animates a line
growing as it accumulates 2,000 data points. The drawnow function displays the changes
after each iteration through the loop.
s = settings;
s.matlab.editor.AllowFigureAnimation.PersonalValue = true;
h = animatedline;
axis([0 4*pi -1 1])
x = linspace(0,4*pi,2000);
2-3
R2019a
for k = 1:length(x)
y = sin(x(k));
addpoints(h,x(k),y);
drawnow
end
Live Editor Output: Interactively clean categorical data and
filter datetime and duration variables in table output
In the Live Editor, you can interactively clean categorical data and filter datetime and
duration variables in table output.
To clean a categorical variable in a table, click the down arrow
to the right of the
variable name and select Edit Categories. Use the available options to create, remove,
and merge categories.
2-4
Environment
To filter a datetime or duration variable in a table, click the down arrow
right of the variable name and select from the available filtering options.
to the
To add the generated code to your live script, click the Update Code button below the
table. Adding the generated code to your live script ensures that the cleaning and
filtering is reproduced the next time you run the live script.
Live Editor Output: Interactively change the data type of
variables in table output
In the Live Editor, you can interactively change the data type of a variable in table output.
Right-click the variable column in the table, select Convert from datatype to, and
select from the available options.
2-5
R2019a
Live Editor Functions: Automatically convert selected code to
a function
Break large scripts or functions into smaller pieces by converting selected code into
functions in files or local functions. With one or more lines of code selected, on the Live
Refactor, and then select from the available
Editor tab, in the Code section, click
options. MATLAB creates a function with the selected code and replaces the original code
with a call to the newly created function.
MATLAB Online: Share folders and collaborate with others
Share your folders with a view-only link, or invite individual collaborators and set their
editing permissions. Invitations can be accepted or declined.
After a folder is shared, you can manage the permissions of invited members, rescind
invitations, or send additional invitations at any time.
Projects: Organize, manage, and share your work using
projects
Create projects in MATLAB to organize and share your work with others. Use projects to
find files required to run your code, manage and share files and settings, and interact
with source control.
2-6
Environment
To create a project from an existing folder of files, in the desired folder, go to the Home
tab, and select New > Project > From Folder. MATLAB creates the project and adds
your existing files to the project.
MATLAB Startup: Execute MATLAB script or function noninteractively
To call a MATLAB script or function non-interactively, start MATLAB with the -batch
option. The option is for non-interactive use in both scripting and command-line
workflows. MathWorks recommends that you use the -batch option instead of the -r
statement option for these cases.
For example, to run unit tests you created for your programs, from the operating system
command prompt, type:
matlab -batch runtests
MATLAB:
• Starts without the desktop
• Does not display the splash screen
• Executes the runtests function
• Logs text to stdout and stderr
• Exits automatically with status
To test if a session of MATLAB is running in batch mode, call the
batchStartupOptionUsed function.
For more information, see matlab (Windows), matlab (macOS), or matlab (Linux).
Toolbox Packaging: Install required add-ons with custom
toolboxes
When creating a custom toolbox, MATLAB detects the add-ons required by the toolbox.
When someone installs your toolbox, the toolbox also downloads and installs the required
add-ons.
2-7
R2019a
Language and Programming
append Function: Combine strings
Combine text in string arrays, character vectors, and cell arrays of character vectors
using the append function.
Unlike the strcat function, append treats all input data types the same. For example, if
an input argument has trailing whitespace characters, then append always keeps them,
even when the argument is a character vector.
MException class: Provide a suggested fix for an uncaught
exception
Provide a suggested fix, using the Correction class, for an exception when it is thrown
and not caught. Use the addCorrection method to add the correction to an
MException object.
Functionality being removed or changed
Folders named resources are not allowed on the MATLAB path
Warns
Starting in R2019a, the resources folder is a reserved folder, and folders with the name
resources are not allowed on the MATLAB path. In previous releases, these folders
were allowed on the MATLAB path.
If a folder named resources is specified when calling the addpath, userpath, or
pathdef functions, MATLAB returns a warning and the folder is not added to the path. If
you have a folder named resources, MATLAB is unable to run any of the contents of that
folder, even if the resources folder is the current folder.
Rename all folders on the path named resources, and move any files you want to run in
MATLAB out of folders named resources.
Cell array expansion is consistent with general array expansion
Behavior change
Starting in R2019a, the dimensions of an expanded cell array are consistent whether you
use curly braces or parentheses for indices. Previously, the output dimensions were
2-8
Language and Programming
different when you did not specify indices for all dimensions. Indexing with curly braces
now matches the previous behavior for indexing with parentheses, which is consistent
with general array expansion.
For more information, see the Compatibility Considerations section of cell.
Structure array expansion is consistent with general array expansion
Behavior change
Starting in R2019a, the dimensions of an expanded structure array are consistent
whether you assign a value to a single field using dot notation or assign an entire
structure to the array. Previously, the output dimensions were different when you did not
specify indices for all dimensions. Assigning to a field using dot notation now matches the
previous behavior of assigning a structure, which is consistent with general array
expansion.
For more information, see the Compatibility Considerations section of struct.
Class properties using size validation no longer unconditionally reshape empty
arrays
Behavior change
In previous releases, if a class defined a property using a size validation that contained
unrestricted dimensions (indicated by a colon, such as (:,:)), then assigning an empty
array of any size to the property resulted in an empty array of size (0,0). For example,
given this class definition:
classdef MyClass
properties
Prop1(:,:)
Prop2
end
end
Assigning an empty array of any dimension to Prop1 always resulted in an empty array of
dimensions (0,0).
obj = MyClass;
obj.Prop1 = double.empty(0,5);
size(obj.Prop1)
ans =
0
0
2-9
R2019a
Assigning an empty array to Prop2 produces the correct result because size validation
with unrestricted dimensions is not used in the class.
obj = MyClass;
obj.Prop2 = double.empty(0,5);
size(obj.Prop2)
ans =
0
5
Starting in R2019a, using unrestricted size validation for properties does not cause the
size of empty arrays assigned to the properties to be reshaped to (0,0). In R2019a, the
same class definition produces these results for assignment to Prop1.
obj = MyClass;
obj.Prop1 = double.empty(0,5);
size(obj.Prop1)
ans =
0
5
Defining classes and packages using schema.m will not be supported in a future
release
Still runs
Support for classes and packages defined using schema.m files will be removed in a
future release. Replace existing schema-based classes with classes defined using the
classdef keyword.
First argument to ismethod must be an object
Behavior change in future release
The ismethod function is documented to look for a method of the object that is specified
as the first input. However, the ismethod function treats string and char inputs as a
class name and looks for the specified method in that class. Therefore, you cannot use
ismethod to find a method of an input object that is a string or char array. In future
releases, ismethod will return true only if the second input is the name of a method of
the first input object. ismethod will not treat the first input as a class name.
For code that uses ismethod with a class name specified as a string scalar or character
vector, you can substitute this expression as an alternative that will work in current and
future versions.
2-10
Language and Programming
any(strcmp('methodName', methods('ClassName')))
Program files larger than 128 MB or with high complexity will not be supported
Behavior change in future release
In a future release, running or opening program files larger than approximately 128MB
will not be supported. For files that contain only code (for example, .m and .p files), this
limit will affect the file size. For files that store more than just code (for example, .mlx
files), it will affect the size of the code. Running statements larger than 128MB, either
directly in the Command Window or using the eval function, also will not be supported.
In addition, code with high levels of complexity, such as a large number of deeply nested
if statements, will not be supported. Currently, these files and code are supported but
can cause errors or unpredictable behavior.
Code that is too large or complex will not run or open in MATLAB, and MATLAB will
display an error.
Large program file or statement sizes often occur when using large portions of code (for
example, over 500 lines) to define variables with constant values. To decrease the size of
these files, consider defining the variables and saving them in a data file (for example, a
MAT-file or .csv file). Then you can load the variables instead of executing code to
generate them. This not only decreases the file size of your program, but can also
increase performance.
0 comentarios
ALAN DENVER
el 22 de Feb. de 2020
Part 5 :
Data Analysis
xcorr and xcov Functions: Compute cross-correlation and
cross-covariance in core MATLAB
You can now compute the cross-correlation and cross-covariance of data using MATLAB.
Previously, xcorr and xcov were only available in the Signal Processing Toolbox™.
detrend Function: Remove piecewise polynomial trends, set
continuity requirements, and specify sample points
The detrend function now offers additional functionality.
• In addition to the constant and linear methods for removing piecewise trends, you can
specify higher degree polynomials. For example, detrend(A,3) removes a cubic
trend from the data in A.
• When supplying break points, you can use the 'Continuous' parameter to specify
whether the fitted trend must be continuous.
• The 'SamplePoints' parameter allows you to define the sample points associated
with the input data.
groupcounts Function: Count the number of group elements
for arrays, tables, and timetables
To count the number of elements in a group, use the groupcounts function.
grouptransform Function: Transform array data by group
In addition to tables and timetables, you can now transform data in an array by group
using the grouptransform function.
filloutliers, isoutlier, and rmoutliers Functions: Detect outliers
using percentiles
The filloutliers, isoutlier, and rmoutliers functions now offer Winsorization for
detecting outliers using the 'percentiles' option.
2-12
Data Analysis
fillmissing and filloutliers Functions: Fill missing and outlier
data using modified Akima interpolation
You can now fill missing and outlier data with modified Akima interpolation using the
'makima' option in the fillmissing and filloutliers functions.
fillmissing Function: Specify missing value locations
To specify the locations of missing data when using the fillmissing function, use the
'MissingLocations' parameter.
min and max Functions: Return index information when
operating on more than one dimension and specify linear
indices
When simultaneously operating on more than one dimension with the min and max
functions, you can now return index information corresponding to the minimum and
maximum values.
You can also return the linear indices corresponding to the minimum and maximum
values of the input array using the 'linear' option.
tall Arrays: Write custom sliding-window algorithms to
operate on tall arrays
The functions matlab.tall.movingWindow and matlab.tall.blockMovingWindow
enable you to write custom algorithms for sliding-window functions to operate on tall
arrays.
tall Arrays: Operate on tall arrays with more functions,
including groupcounts, intersect, and svd
The functions listed in this table now support tall arrays as inputs. For a complete list of
supported functions, type methods tall. For more information on usage and limitations,
see the Extended Capabilities section at the bottom of each reference page.
2-13
R2019a
addvars
movevars
cospi
normalize
groupcounts
removevars
grouptransform
sinpi
inner2outer
splitvars
intersect
svd
mergevars
union
In addition, some functions have removed limitations with tall arrays.
Functions
Added Support
stack
The two-output syntax [S,iu] =
stack(___) now supports tall arrays. The
second output returns indices that describe
the mapping of rows in the stacking
operation.
Previously, multiple outputs were not
supported for tall arrays.
groupsummary
Grouped calculations on tall matrices and
arrays are now supported.
Previously, the first input was required to
be a tall table or tall timetable.
Functionality Being Removed or Changed
Default random number generator change for tallrng
Behavior change
Starting in R2019a, the default random number generator for tallrng is threefry. This
generator offers performance enhancements for parallel calculations over the old default.
In releases up to R2018b, the default random number generator for tallrng was
combRecursive.
With a different default generator, MATLAB will generate different sequences of random
numbers by default in the context of tall arrays. However, the statistics of these
2-14
Data Analysis
calculations will remain unaffected. Therefore, you should update any code that relies on
the specific random numbers being generated. However, most calculations on the random
numbers should be unaffected.
To set the generator to the settings used by default in R2018b and earlier releases, use
the command:
tallrng(0,'combRecursive')
2-15
R2019a
Data Import and Export
readmatrix, readvars, and readcell Functions: Read tabular
data as a matrix, variables, or a cell array
Read column-oriented data from text or spreadsheet files into a matrix, variables, or a cell
array.
• readmatrix — Read homogeneous column-oriented data into a matrix.
• readvars — Read column-oriented data into variables. Each variable corresponds to
a column of data in the file.
• readcell — Read heterogeneous data into a cell array.
writematrix and writecell functions: Write tabular data from a
matrix or cell array to a text or spreadsheet file
Write data from a matrix or a cell array to a text or spreadsheet file.
• writematrix — Write a homogeneous array to a file.
• writecell — Write a cell array to a file.
readtimetable and writetimetable Functions: Read and write
timetables
Read and write timetables in MATLAB.
• Use the readtimetable function to read timetables from text or spreadsheet files.
• Use the writetimetable function to write timetables to text or spreadsheet files.
detectImportOptions Function: Improve detection of import
options for text and spreadsheet files
Improve the detection of import options for text and spreadsheet files by passing
additional information to the detectImportOptions function using these name-value
pairs.
2-16
Data Import and Export
• 'ThousandsSeparator' — Character separating thousands groups (numeric
variables only)
• 'DecimalSeparator' — Character separating integer part from fractional part
(numeric variables only)
• 'TrimNonNumeric' — Remove non-numeric characters from numeric variables
(numeric variables only)
• 'ConsecutiveDelimitersRule' — Procedure to handle consecutive delimiters
(text files only)
• 'LeadingDelimitersRule' — Procedure to handle leading delimiters (text files
only)
• 'TreatAsMissing' — Text to interpret as missing data (text files only)
• 'ReadRowNames' — Read first column as row names
• 'ReadVariableNames' — Read first row as variable names
For more information, see the setvaropts and detectImportOptions reference
pages.
parquetread, parquetwrite, and parquetinfo Functions: Read,
write, and get information from Parquet files
Import and export column-oriented data from Parquet files in MATLAB. Parquet is a
columnar storage format that supports efficient compression and encoding schemes. To
work with the Parquet file format, use these functions.
• parquetread — Read columnar data from a Parquet file.
• parquetwrite — Write columnar data to a Parquet file.
• parquetinfo — Get information about a Parquet file.
For more information on the Parquet file format, see https://parquet.apache.org/.
write Function: Write tall arrays to Parquet files
The write function now supports writing tall arrays to Parquet files. To write a tall array,
set the FileType parameter to 'parquet', for example:
write('C:\myData',tX,'FileType','parquet')
2-17
R2019a
Import Tool: Generate improved code when importing from
text files
Import Tool now functions consistently across different platforms and generates code
that is easy to read for importing text files. For more information, see Import Text File
Data Using Import Tool.
thingSpeakRead and thingSpeakWrite Functions: Read or
write data to the ThingSpeak IoT platform
Access IoT data in ThingSpeak™ channels:
• Use thingSpeakRead to read data from ThingSpeak channels.
• Use thingSpeakWrite to write data to ThingSpeak channels.
For more information on the ThingSpeak platform, see https://thingspeak.com/.
writetable and imwrite Functions: Write to web-based storage
services like Amazon Web Services and Azure Blob Storage
Write tabular data and image files to remote locations using the writetable and
imwrite functions. When writing data to remote locations, you must specify the full path
using a uniform resource locator (URL). For example, write a csv file and a jpg file to
Amazon S3 Cloud:
writetable(T,'s3://bucketname/path_to_file/my_text_file.csv');
imwrite(I,'s3://bucketname/path_to_file/my_image.jpg');
For more information on setting up MATLAB to access your online storage service, see
Work with Remote Data.
ParquetDatastore Object: Create a datastore for a collection
of Parquet files
Read a collection of Parquet files into MATLAB workspace using parquetDatastore.
For more information on the Parquet file format, see https://parquet.apache.org/.
2-18
Data Import and Export
ImageDatastore Object: Create a subset of an existing
datastore
Create a subset of an image datastore using the subset method.
DsFileSet Object: Create a subset of a file collection
You can create a subset of a DsFileSet object by using the subset method. The
DsFileSet object helps you manage the iterative processing of large collections of files.
FileDatastore Object: Read large files by importing the file in
smaller portions
Read and process large files in smaller portions. For example, you can create a datastore
that reads one array at a time from a large MAT-file that does not fit in the available
memory. To set up your datastore to perform partial reads, use these name-value pairs:
'ReadMode', 'PreviewFcn', and 'BlockSize'.
For more information, see fileDatastore.
Datastores: Combine and transform datastores
Perform combine and transform operations on existing datastores.
• combine — Combine two or more datastores and return a new datastore representing
the underlying datastores.
• transform — Transform an input datastore by using a specified transformation
function and return the transformed datastore.
Custom Datastore: Read Hadoop based data from files,
databases, and other non-file-based locations
Author a custom datastore to access data stored in files or non-file-based data sources
such as a databases using matlab.io.datastore.HadoopLocationBased mixin. Use
this extension to specify the location of your data in Hadoop®. A custom datastore with
the HadoopLocationBased mixin makes computations more efficient by leveraging the
location of the data. With your custom datastore you can perform big data analysis by
using tall arrays and mapreduce.
2-19
R2019a
For more information on the custom datastore framework, see Develop Custom Datastore.
VideoReader function: Generate C and C++ code
The VideoReader function supports C and C++ code generation using MATLAB Coder™.
ind2rgb function: Generate C and C++ code
The ind2rgb function supports C and C++ code generation using MATLAB Coder.
Scientific File Format Libraries: NetCDF Library upgraded to
version 4.6.1
The NetCDF library is upgraded to version 4.6.1.
web function: Open external sites in system browser instead
of MATLAB browser
You can change the default behavior of the web function to open external sites in your
system browser instead of the MATLAB browser. Using the system browser is
recommended when opening external sites. To change the default behavior, go to the
Home tab, and in the Environment section, click Preferences. Select MATLAB > Web,
and in the System Web browser section, select Use system web browser when
opening links to external sites (recommended).
Functionality being removed or changed
NumberOfChannels property of the audioplayer and audiorecorder Objects is not
recommended
Still runs
The NumberOfChannels property of the audioplayer and audiorecorder objects is
not recommended. Use the name NumChannels instead. To update your code, change
instances of NumberofChannels to NumChannels. The values of the properties are the
same. There are no plans to remove the NumberOfChannels property at this time.
web Function
Behavior change in future release
2-20
Data Import and Export
In future releases, the web function will open external sites using your system browser by
default. Currently, the web function opens external sites using the MATLAB browser.
Using the system browser is recommended when opening external sites.
To change the default browser, go to the Home tab, and in the Environment section,
click Preferences. Select MATLAB > Web and in the System Web browser section,
select Use system web browser when opening links to external sites
(recommended).
hdftool is not recommended
Still runs
In a future release, hdftool will be removed. To import HDF4 or HDF-EOS files, use the
hdfread function instead.
csvread and csvwrite functions are not recommended
Still runs
csvread and csvwrite are not recommended. Use readmatrix and writematrix
instead. There are no plans to remove csvread and csvwrite.
This table shows typical usages of csvread and csvwrite and how to update your code
to use readmatrix and writematrix instead.
Not Recommended
Recommended
M = csvread(filename)
M = readmatrix(filename)
csvwrite('mydata.txt',M)
writematrix(M,'mydata.txt')
For more information, see readmatrix and writematrix.
dlmread and dlmwrite functions are not recommended
Still runs
dlmread and dlmwrite are not recommended. Use readmatrix and writematrix
instead. There are no plans to remove dlmread and dlmwrite.
This table shows typical usages of dlmread and dlmwrite and how to update your code
to use readmatrix and writematrix instead.
2-21
R2019a
Not Recommended
Recommended
M = dlmread(filename)
M = readmatrix(filename)
dlmwrite('mydata.txt',M)
writematrix(M,'mydata.txt')
For more information, see readmatrix and writematrix.
xlsread and xlswrite functions are not recommended
Still runs
xlsread and xlswrite are not recommended. Instead of xlsread and xlswrite:
• Use readtable and writetable for reading and writing mixed numeric and text
data.
• Use readmatrix and writematrix for reading and writing homogenous text or
numeric data.
• Use readcell and writecell for reading and writing mixed numeric and text data.
There are no plans to remove xlsread and xlswrite.
This table shows typical usages of xlsread and xlswrite and how to update your code
to use the recommended read and write functions.
Not Recommended
Recommended
Read spreadsheet data as a matrix using Read spreadsheet data as a table:
xlsread:
T = readtable(filename)
M = xlsread(filename)
However, to continue reading your data as a
matrix, use:
M = readmatrix(filename)
Read spreadsheet data as a cell array
using xlsread:
[~,~,C] = xlsread(filename)
Import spreadsheet data as a table:
T = readtable(filename)
However, to continue importing your data as a
cell arrary, use:
C = readcell(filename)
2-22
Data Import and Export
Not Recommended
Read a specific sheet and range as a
matrix using xlsread:
M = xlsread(filename,sheet,range)
Recommended
Read a specific sheet and range as a table:
T = readtable(filename,'Sheet',sheet,'Range',range)
However, to continue reading your data as a
matrix, use:
M = readmatrix(filename,'Sheet',sheet,'Range',range
Read a specific sheet and range as a cell Read a specific sheet and range as a table:
array using xlsread:
T = readtable(filename,'Sheet',sheet,'Range',range)
[~,~,C] = xlsread(filename,sheet,range)
However, to continue reading your data as a
cell array:
C = readcell(filename,'Sheet',sheet,'Range',range)
Write tabular data to spreadsheets using To write tabular data to spreadsheets, use one
xlswrite:
of these options instead.
xlswrite(filename,M)
Write a table:
writetable(T,filename)
Write a matrix:
writematrix(M,filename)
Write a cell array:
writecell(C,filename)
For more information, see readmatrix, writematrix, readcell, writecell,
readtable, and writetable.
HadoopFileBased is not recommended
Still runs
HadoopFileBased is not recommended. Use HadoopLocationBased instead. There are
no plans to remove HadoopFileBased.
2-23
R2019a
Starting in R2019a, use the HadoopLocationBased mixin to add Hadoop support to
your custom datastore. The HadoopLocationBased mixin provides support for non-filebased data where as HadoopFileBased supports file-based data only.
For more information on the custom datastore framework, see Develop Custom Datastore.
2-24
Mathematics
Mathematics
Solve assignment problem with matchpairs and equilibrate
New functions enable you to solve the assignment problem in a variety of contexts.
• matchpairs — Create a linear mapping between the rows and columns of a cost
matrix. This assigns rows to columns in such a way that the global cost is minimized.
• equilibrate — Permute and rescale a matrix A such that the new matrix B =
R*P*A*C has only 1s and -1s on its diagonal, and all off-diagonal entries are not
greater than 1 in magnitude. When computing a preconditioner to iteratively solve a
linear system, use equilibration to improve the condition of a matrix and allow for
improved preconditioners.
graph and digraph Objects: Construct graphs with categorical
nodes
The graph, digraph, and addedge functions now support categorical node names as
inputs. This enables you to use data that is imported as categorical to create a graph,
without the need for data type manipulation.
2-25
R2019a
Graphics
parallelplot Function: Visualize tabular or matrix data with
multiple columns by using a parallel coordinates plot
To create a parallel coordinates plot, use the parallelplot function. Rows of the input
data correspond to lines in the plot, and columns of the input data correspond to
coordinates in the plot. To group the lines in the plot, you can use either the
'GroupVariable' name-value pair argument with tabular data or the 'GroupData'
name-value pair argument with matrix data.
Data Tips: Pin and customize data tips in charts
The data tips that appear as you hover over a chart become persistent (pinned) when you
click them. Clicking a second time unpins the data tip.
For some types of charts, you can customize the contents of the data tips. For example,
you can edit the data tip labels, change the displayed values, or change the font size. Also,
you can add or delete rows from the data tips. Charts that support these customizations
include Scatter, Stair, Stem, Line, and Surface objects with a DataTipTemplate
property.
• To edit the labels interactively, double-click a label, type the text you want, and then
click outside the data tip. To make other customizations interactively, right-click the
data tip and select Edit Properties.... Use the fields in the Property Inspector that
opens to make any changes.
• To customize the data tip programmatically, use the DataTipTemplate property of
the chart object. For example, this code plots sample patient data from a table as a
scatter chart. Then it changes the font size and labels of the data tips. For more
information, see DataTipTemplate.
tbl = readtable('patients.xls');
s = scatter(tbl.Weight,tbl.Height);
s.DataTipTemplate.FontSize = 12;
s.DataTipTemplate.DataTipRows(1).Label = 'Weight';
s.DataTipTemplate.DataTipRows(2).Label = 'Height';
You can add a new row to the data tip using the dataTipTextRow function. For
example, add a third row that shows the patient name from the table.
2-26
Graphics
s.DataTipTemplate.DataTipRows(3) = dataTipTextRow('Name',tbl.LastName);
Axes Interactions: Customize chart interactions such as
dragging to pan or scrolling to zoom
Create a customized set of chart interactions by setting the Interactions property of
the axes. These interactions are built into the axes and are available without having to
select any buttons in the axes toolbar. Some types of interactions are enabled by default,
depending on the content of the axes.
For more information, see Control Chart Interactivity.
Ruler Panning: Pan an axis to change its limits without having
to use the pan tool
Drag an axis to change the limits along a dimension of a plot. This functionality is
available for most Cartesian plots, even when the pan tool in the axes toolbar is disabled.
Property Inspector: Navigate and control visibility of graphics
objects interactively
You can use the object browser that appears at the top of the Property Inspector to
navigate and control the visibility of graphics objects. When you select an object using the
object browser, the object appears selected in the figure and the properties appear in the
inspector.
The object browser has a collapsed view and an expanded view.
• The collapsed view (default view) shows the currently selected object and its direct
hierarchy. Click one of the object names to see its properties in the Property Inspector.
2-27
R2019a
• The expanded view shows the graphics object hierarchy of the figure. Right-click an
object name to show, hide, or delete the graphics object. Select multiple objects using
Ctrl+click.
Geographic Plots: Geographic rulers, scale bar, CurrentPoint,
and ginput
Plots on geographic axes include customizable rulers and a scale bar.
2-28
Graphics
Use the geotickformat function to customize rulers.
GeographicAxes support the CurrentPoint property. Use this property to get the
current coordinates of the mouse pointer on a geographic axes.
Graphics Export: Export axes with tighter cropping using the
axes toolbar
Click or tap the export button in the axes toolbar to save the axes as an image or PDF file.
The saved content is tightly cropped around the axes with minimal white space.
2-29
R2019a
Chart Resizing: Resize charts with improved layouts
The layout is improved when you resize a chart that can be a child of a figure (such as a
heatmap). This automatic resizing behavior adjusts the font sizes and spacing between
elements in the chart to provide the best possible presentation for the new size.
Changing the FontSize property of a chart disables the automatic resizing of the fonts.
Colors Values: Specify colors using hexadecimal color codes
Specify hexadecimal color codes when setting the color of graphics objects. For example,
set(gca,'XColor','#FF8800') sets the x-axis color to orange. Use either the six-digit
or three-digit form to specify a color. The characters are not case-sensitive. Thus,
'#FF8800', '#ff8800', '#F80', and '#f80' are equivalent.
Categorical Values: Specify categorical arrays for functions
and objects that use lists of text
Many functions and object properties that use lists of text items now accept categorical
arrays in addition to cell arrays and string arrays. When you specify a categorical array,
MATLAB uses the values in the array, not the categories. Thus you might need to write
additional code to extract the values you want to use. For example, this code finds the
unique entries of the cities categorical array before setting the x-axis tick labels.
bar([10 20 30])
cities = categorical({'Boston','Boston','Berlin','Paris','Berlin'});
xticklabels(unique(cities))
See the documentation for a specific function or object to determine whether it accepts
categorical values.
rendererinfo Function: Get renderer information for any axes
Use the rendererinfo function to get information about the graphics renderer used for
any axes or chart that can be a child of a figure.
2-30
Graphics
Compatibility Considerations
Use the rendererinfo function instead of the opengl function to get information about
the graphics renderer.
Functionality being removed or changed
Using the opengl function to get information about the graphics renderer is not
recommended
Still runs
Using the opengl function to get information about the graphics renderer is not
recommended. Specifically, these syntaxes are not recommended:
• opengl info
• d = opengl('data')
There are no plans to remove support for these syntaxes at this time. Instead of calling
opengl to get the renderer information, call the rendererinfo function instead:
info = rendererinfo(ax)
Specify ax as any type of axes or a chart that can be a child of a figure (such as a
heatmap). The output is a structure containing most of the same information as the
opengl function provides.
Fields in opengl Structure
Corresponding Fields in rendererinfo
Structure
d.Version
info.Version
d.Vendor
info.Vendor
d.Renderer
info.RendererDevice
d.RendererDriverVersion
info.Details.RendererDriverVersio
n
d.RendererDriverReleaseDate
info.Details.RendererDriverReleas
eDate
d.MaxTextureSize
info.Details.MaxTextureSize
d.Visual
No longer needed
2-31
R2019a
Fields in opengl Structure
Corresponding Fields in rendererinfo
Structure
d.Software
This information is stored in
info.GraphicsRenderer, but to get the
equivalent logical value, use
strcmp(info.GraphicsRenderer,'Ope
nGL Software')
Heatmaps interpret text using TeX markup
Behavior change
Starting in R2019a, heatmaps created with the heatmap function interpret text using TeX
markup instead of displaying the literal characters. If you want to use a TeX markup
character in regular text, such as an underscore (_), then insert a backslash (\) before the
character you want to include. The backslash is the TeX escape character. For more
information on using TeX markup, see the Interpreter property of the text object.
2-32
App Building
App Building
uiimage Function: Display an icon, logo, or picture in apps and
on the App Designer canvas
To display a picture, icon, or logo in your app, call the uiimage function
programmatically or, in App Designer, drag and drop an image component from the
Component Library onto the canvas.
Image components are supported only in App Designer apps and in figures created with
the uifigure function.
uitable Function: Sort tables interactively when using table
arrays
To create tables that can be sorted interactively, use table arrays and configure the
ColumnSortable property of the Table object. Use the DisplayData property and a
DisplayDataChangedFcn callback if you want to update your visualizations based on
how a user sorts a table containing table data.
Auto Resize: Automatically resize components when an app is
made smaller
When a parent container is resized smaller than its initial size, AutoResizeChildren
now reduces the white space between components and shrinks the components
themselves to maintain usability. For more information, see Managing Resizable Apps in
App Designer.
Scrolling Grids: Create apps with scrollable grids
Enable interactive scrolling in your grid layout manager by setting the Scrollable
property of the grid to 'on'. See uigridlayout for more information.
App Designer: Create apps that automatically reflow content
based on device size
Create 2-panel or 3-panel preconfigured apps that automatically resize and reflow content
based on screen size, screen orientation, and platform. Use apps with auto-reflow if you
2-33
R2019a
expect to run or share your apps across multiple environments or desktop resolutions. For
more information, see Apps with Auto-Reflow.
App Designer: Add and configure a grid layout manager on
the App Designer canvas
Structure the layout of your app by dragging a grid layout manager from the Component
Library onto the canvas. To configure the grid layout in Design View, select the
icon
from the upper-left hand corner of the grid, or right-click and select Configure grid
layout. Then, select a row or column to edit. For more information, see the
uigridlayout function or GridLayout Properties.
Grid layout managers are supported only in App Designer apps or in figures created with
the uifigure function.
App Designer: Rearrange the order of callbacks
To rearrange the order of callbacks, go to the Code Browser, select the callback you
wish to move, and then drag the callback into a new position in the list. This also
repositions the callback in the editor.
0 comentarios
ALAN DENVER
el 22 de Feb. de 2020
Part 6 et Final ( sorry if it's too much lol )
App Building
App Designer: Control font, code, and autosave settings using
MATLAB Preferences
Control these settings through the Preferences dialog box
• Autocoding for patterns like parentheses, block endings, and comment wrapping
• Keyboard preferences for automatic code suggestions and completions
• Autosave preferences upon clicking away from a file
• Font size preference for App Designer Code View
Changes to the autosave and font size preferences apply to only the App Designer Editor.
When you set the autocoding or keyboard preferences, the change applies to the MATLAB
Editor and to App Designer.
App Designer: Access context-sensitive help in Code View
To open the documentation for a component, function, or callback in your code, highlight
the element and then press F1, or right-click and choose help for the code element you
selected.
App Designer: Zoom in App Designer
Hold Ctrl and move the scroll wheel in the App Designer window to zoom in or out. To
return to the default scale, press Ctrl+0.
Graphics Support: Explore data using axes toolbar and data
tips in apps created with the uifigure function
Use the axes toolbar and data tips to explore plotted data interactively in App Designer
apps and in figures created with the uifigure function. The axes toolbar and data tips
are on by default for axes and uiaxes objects in a uifigure.
Compatibility Considerations
• Axes toolbar — In previous releases, the axes toolbar was not enabled for axes or
uiaxes objects in a uifigure object. Now, it is enabled by default. You can turn it off
by setting the Visible property of the AxesToolbar object to 'off'. For more
information, see AxesToolbar Properties.
2-35
R2019a
• Data tips — In previous releases, data tips were not enabled for axes or uiaxes
objects in a uifigure object. Now, to control whether the axes interactions are
enabled, use the disableDefaultInteractivity and
enableDefaultInteractivity functions. For example,
uf = uifigure;
ax = axes(uf);
plot(ax,rand(5))
disableDefaultInteractivity(ax)
Deployed Web Apps: Share resizeable apps or create apps
that open web pages
In deployed web apps you can now do the following:
• Interactively resize your web app.
• Program your web app to open another URL using the web function.
For information about other new features of deployed web apps, see Release Notes
(MATLAB Compiler).
MATLAB Online: Create and edit App Designer apps using
MATLAB Online
Create or edit apps in MATLAB Online™ using the App Designer development
environment (supported only for Google Chrome browsers).
App Testing Framework: Perform hover gesture on axes, UI
axes, and UI figures
The matlab.uitest.TestCase.hover method enables you to perform hover gestures
in tests on axes, UI axes, and UI figure objects. For more information, see the hover
reference page.
2-36
App Building
App Testing Framework: Perform press gesture on axes, UI
axes, and UI figures
The matlab.uitest.TestCase.press method enables you to perform press gestures
in tests on UI axes and UI figure objects. For more information, see the press reference
page.
App Testing Framework: Perform type gesture on date picker
objects
The matlab.uitest.TestCase.type method enables you to perform type gestures on
date picker objects. For more information, see the type reference page.
Functionality Being Removed or Changed
javacomponent function and JavaFrame property will be removed in a future
release
Warns
The undocumented javacomponent function and JavaFrame property will be removed
in a future release. The JavaFrame property still runs, but returns a warning. The
javacomponent function still runs, without warning, but will begin to warn in an
upcoming release. Users are encouraged to update their code to use documented
alternatives. For a list of documented functionality you can use instead, see Java Swing
Alternatives for MATLAB Apps on mathworks.com.
Support for running deployed web apps in Internet Explorer will be removed in a
future release
Still runs
Support for running deployed web apps in Internet Explorer will be removed in a future
release. Use the current versions of Google Chrome (recommended), Safari, Firefox, or
Microsoft Edge to run deployed web apps instead.
2-37
R2019a
Performance
MATLAB and Simulink startup on macOS platforms
To prevent performance regression at startup for MATLAB and Simulink® on macOS
platforms, MathWorks recommends using MATLAB R2018b Update 4 or later with macOS
10.13.6 Update or later.
sortrows Function: Sort rows of large matrices faster
For large matrices, you can now sort rows faster using the sortrows function.
For example, on a test system, this code runs faster in R2019a than in previous releases.
A = repmat(eye(200),500,1);
sortrows(A)
uitable Function: Faster performance using table arrays
Tables created with the uitable function and with data specified as a table array have
better rendering performance and higher frame rates while scrolling. Tables that use
table arrays render up to 40% faster, and interaction performance (like scrolling) is up
to 75% faster. For example, on a test system, this code renders the tables faster in
R2019a than in previous releases.
rows = 10000;
columns = 25;
data = array2table(randi(30, [rows, columns]));
fig = uifigure;
tbl = uitable(fig, 'Data', data);
For more information about using table arrays in Table UI components, see Table Array
Data Types in App Designer Apps.
2-38
Software Development Tools
Software Development Tools
checkcode Function: Get the modified cyclomatic complexity
of functions
Use the checkcode function with the 'modcyc' option to get the modified cyclomatic
complexity of each function in a file. The modified cyclomatic complexity for a function is
equal to the McCabe complexity except for one difference. McCabe complexity counts
each individual case within a switch statement as 1, while modified cyclomatic
complexity counts the entire switch statement as 1. In general, switch statements are
simpler than nested if-elseif-else statements and therefore, the modified cyclomatic
complexity is often considered a better measure of code complexity.
Source Control Integration: Synchronise MATLAB Git status
with external Git clients
If you use an external Git client, MATLAB now listens to external changes to working
copies of .git folders and refreshes the file status if needed. MATLAB keeps the Git file
status in sync when using another Git client, both in the MATLAB current folder and in a
project.
Unit Testing Framework: Display code coverage metrics in
HTML format
The matlab.unittest.plugins.codecoverage.CoverageReport class provides an
HTML code coverage report format to display code coverage metrics. Use this format
with matlab.unittest.plugins.CodeCoveragePlugin to produce the report.
Unit Testing Framework: Specify sources for collections of
code coverage data with runtests
The runtests function enables you to specify the source code files to include in the code
coverage report. Use the ReportCoveragefor name-value input to specify the files or
folders containing source files to include in the tests.
2-39
R2019a
Unit Testing Framework: runperf collects more samples to
achieve its target margin of error
The default maximum number of sample measurements that runperf makes when
running performance measurements has increased to 256. Specify the number of sample
measurements using the
matlab.perftest.TimeExperiment.limitingSamplingError method.
Unit Testing Framework: Return performance test results as
TimeResult arrays
The runperf function now returns a matlab.perftest.TimeResult array containing
the results of the specified performance tests. This class derives from the
matlab.unittest.measurement.MeasurementResult class, which is now an
abstract class.
Unit Testing Framework: Load previously saved
MeasurementResult objects as DefaultMeasurementResult
MeasurementResult objects saved in previous releases are loaded as
matlab.unittest.measurement.DefaultMeasurementResult objects. This class is
derived from the MeasurementResult class.
Unit Testing Framework: Use
matlab.unittest.fixtures.Fixture.onFailure method only in
subclasses
The onFailure method now has protected access. In previous releases, onFailure
had public access. This change better supports the use of onFailure to produce
additional diagnostics in case of a failure during fixture setup or teardown in classes
derived from Fixture.
Unit Testing Framework: Compare tables that contain no rows
In previous releases, for tables that had no rows (that is, that had a first size dimension of
zero), the matlab.unittest.constraints.IsEqualTo constraint did not compare the
2-40
Software Development Tools
table column variables when determining equality. Now, IsEqualTo always compares the
size and type of each column variable.
For example, comparing these two tables fails now because the column variables are
different types (double and cell).
tc = matlab.unittest.TestCase.forInteractiveUse;
a = table(zeros(0,2));
b = table({});
tc.verifyEqual(a,b)
Verification failed.
--------------------Framework Diagnostic:
--------------------verifyEqual failed.
--> Path to failure: <Value>.Var1
--> Classes do not match.
Actual Class:
double
Expected Class:
cell
Actual double:
0×2 empty double matrix
Expected cell:
0×0 empty cell array
Actual Value:
0×1 empty table
Expected Value:
0×1 empty table
Unit Testing Framework: Create test suite array from tests in
project
The fromProject method enables you to create a test suite array from the files in a
project that are labeled with the Test classification. For more information, see the
matlab.unittest.TestSuite.fromProject reference page.
2-41
R2019a
Unit Testing Framework: Run tests from files in project using
runtests or testsuite
Run test files from projects using the runtests or testsuite functions. The
IncludeReferenceProjects name-value pair argument enables you to include in the
test suite files from a project that are labeled with the Test classification.
Unit Testing Framework: Specify verbosity enumeration as a
string or character vector
You can specify the verbosity level argument for the following methods as a string scalar
or character vector that correspond to the matlab.unittest.Verbosity enumeration
member name.
• matlab.unittest.TestCase.log
• matlab.unittest.TestRunner.withTextOutput
• matlab.unittest.plugins.TestRunProgressPlugin
• matlab.unittest.plugins.LoggingPlugin.withVerbosity
• matlab.unittest.plugins.DiagnosticsOutputPlugin
App Testing Framework: Perform hover gesture on axes, UI
axes, and UI figures
The matlab.uitest.TestCase.hover method enables you to perform hover gestures
in tests on axes, UI axes, and UI figure objects. For more information, see hover.
App Testing Framework: Perform press gesture on axes, UI
axes, and UI figures
The matlab.uitest.TestCase.press method enables you to perform press gestures
in tests on UI axes and UI figure objects. For more information, see press.
2-42
Software Development Tools
App Testing Framework: Perform type gesture on date picker
objects
The matlab.uitest.TestCase.type method enables you to perform type gestures on
date picker objects. For more information, see type.
Mocking Framework: Create mocks for classes that use
custom metaclasses
The unit testing framework can now create mocks for classes that use custom
metaclasses to define custom class, property, method, and event attributes.
Mocking Framework: Create mocks for classes that use
property validation
The unit testing framework can now create mocks for classes that use property validation.
For information on property validation, see Validate Property Values.
Mocking Framework: Specify which methods to mock
When creating a mock object, you can control which methods are mocked in the test case.
Use the createMock method with the MockMethods name-value pair argument to
specify the method to mock. This feature enables tests to mock only those methods that
are important to the test case, which can improve performance when superclasses define
many methods.
Functionality being removed or changed
matlab.unittest.fixtures.Fixture.onFailure method has protected access
Behavior change
In release R2019a, the onFailure method Access attribute is changed from public to
protected. This change restricts the use of onFailure to classes derived from
Fixture.
matlab.unittest.constraints.IsEqualTo always compares table column variables
Behavior change
2-43
R2019a
In release R2019a, the IsEqualTo constraint always compares the size and type of
column variables.
2-44
External Language Interfaces
External Language Interfaces
C++: Use C++ classes from third-party libraries in MATLAB
If you have a library that exports C++ constructs, including classes, functions and
enumerations, then you can use this functionality directly in MATLAB. For more
information, see C++ Libraries.
If you have a C shared library, then use the loadlibrary function as described in C
Libraries.
Python: Version 3.7 support
MATLAB now supports CPython 3.7, in addition to existing support for 2.7, 3.5, and 3.6.
For more information, see Install Supported Python Implementation.
Compatibility Considerations
To start the MATLAB engine asynchronously from Python 3.7, use the
(background=True) keyword argument for matlab.engine.start_matlab. To call a
MATLAB function asynchronously, use the background=True keyword argument for
matlab.engine.MatlabEngine. Do not use the async argument for either function,
since it is a keyword in Python 3.7. You also can use the background argument for all
supported versions of Python.
Python engine: Data type support
The Python engine now supports this functionality:
• Convert MATLAB strings to Python strings
• Pass function handles to Python with the feval command
• Pass MATLAB value objects as opaque objects
C++ MEX: Execute MEX function out of process
Run C++ MEX functions in processes that are separate from the MATLAB process. You
can run multiple MEX functions in the same process and can create multiple processes to
2-45
R2019a
execute MEX functions. For more information, see Out-of-Process Execution of C++ MEX
Functions.
MEX functions: Use customer version of Boost library
Although MATLAB builds with Boost library version 1.56.0, as of MATLAB R2018a, you
can use any Boost library version in a MEX function.
MATLAB Data Array: Support for row-major memory layout
Create a matlab::data::Array with data memory layout specified as column-major
(default) or row-major. For more information, see the memoryLayout parameter in
createArrayFromBuffer. To determine the memory layout for an existing
matlab::data::Array, call getMemoryLayout.
Compiler support changed for building MEX files and
standalone MATLAB engine and MAT-file applications
Support
Compiler
Platform
Added
Intel Parallel Studio XE 2019 with Microsoft Visual Windows
Studio 2015 and 2017 for C, C++, and Fortran
Added
Intel Parallel Studio XE 2019 for Fortran
macOS
To ensure continued support for building your MEX-files, consider upgrading to another
supported compiler. For an up-to-date list of supported compilers, see the Supported and
Compatible Compilers website.
2-46
Hardware Support
Hardware Support
MATLAB Support Package for Parrot Drones: Control Parrot
Mambo FPV drone from MATLAB and acquire sensor data
The MATLAB Support Package for Parrot® Drones is available from release R2019a
onwards.
The support package includes functions to pilot a Parrot Mambo FPV drone by sending
MATLAB commands to control its direction, speed, and orientation. You can also read the
flight navigation data such as speed, height, and orientation using MATLAB commands.
Deploy Sense HAT functions on Raspberry Pi hardware
These Sense HAT functions from the MATLAB Support Package for Raspberry Pi™
Hardware are enhanced to generate code: sensehat, readHumidity, readPressure,
readTemperature, readAngularVelocity, readAcceleration,
readMagneticField, readJoystick, displayImage, writePixel, and
clearLEDMatrix. You can now deploy these functions on the hardware.
Functionality being changed or removed
The i2cdev and spidev functions will be removed in a future release
Warns
Use device instead of i2cdev and spidev to connect to I2C or SPI devices on Arduino®
hardware.
The property Pins of servo object will be removed in a future release
Warns
Use the property Pin instead of Pins to get the pin number of the Arduino hardware and
the Adafruit® Motor Shield V2 for Arduino hardware to which the servo motor is
connected. For more information, see Connection to servo motor on Arduino and
Connection to servo motor on AdafruitMotor Shield V2.
The class arduinoio.LibraryBase will be removed in a future release
Warns
2-47
R2019a
Use the class matlabshared.addon.LibraryBase instead of
arduinoio.LibraryBase for deriving Arduino add-on libraries.
MATLAB support for Adafruit Bluefruit EZ-Link Shield and Programmer will be
removed in a future release
Warns
The support for AdafruitBluefruit EZ-Link Shield and Programmer will be removed in a
future release
MATLAB support for Arduino hardware boards has been removed
Errors
These Arduino hardware boards are no longer supported:
• Arduino Fio
• Arduino Mini
• Arduino Pro
2-48
3
R2018b
Version: 9.5
New Features
Bug Fixes
Compatibility Considerations
R2018b
Desktop
Live Editor: Organize live scripts using additional subheading
styles
Format text in live scripts using the new Heading 2 and Heading 3 text styles. To apply
a text style, go to the Live Editor tab and in the Text section, select any of the options
under the Text Style drop-down.
For more information, see Format Files in the Live Editor.
Live Editor: Navigate within a live script using internal
hyperlinks
Use internal hyperlinks to navigate to locations within a live script. To insert an internal
hyperlink, go to the Insert tab and click
Hyperlink. Enter your display text, select
Internal Hyperlink, and then click anywhere in the document to select the target.
Live Editor: Filter table output interactively, and then add the
generated code to the live script
In the Live Editor, you can filter table data interactively. To filter data in a table, click the
down arrow
to the right of a variable name in the table and select from the available
filtering options.
3-2
Desktop
To add the generated code to your live script, use the Update Code button below the
table. Adding the generated code to your live script ensures that the sorting is
reproduced the next time you run the live script.
Live Editor: Create new and open existing live scripts faster
New and existing live scripts open faster than in previous releases.
Live Editor: Change case of text or code
In the Live Editor, you can change the case of selected text or code from all uppercase to
lowercase, or vice versa. To change the case, select the text, right-click, and select
Change Case. You also can press Ctrl+Shift+A. If the text contains both uppercase and
lowercase text, MATLAB changes the case to all uppercase.
In MATLAB Online, this feature also is available in the Editor.
Comparison Tool: Merge two versions of a live script or
function
When comparing live scripts or live functions using the Comparison Tool, you can merge
changes from one file to the other. Merging changes can be useful when resolving
conflicts between different versions of a file.
3-3
R2018b
To merge two live scripts or functions, go to the Live Editor tab and in the File section,
click Compare. A new window opens and displays the two files side by side. Select the
Merge Mode button to start the merge.
Use the
button to replace content in the right pane with content from the left pane.
The right pane contains the merged result. To save the result, click
Save Result.
For more information, see Compare and Merge Live Code.
Add-On Manager: Install and manage multiple versions of a
custom toolbox
You can install multiple versions of a custom toolbox in the Add-On Manager. Having
multiple versions of a custom toolbox installed is useful if you regularly use multiple
versions and switch between them.
To install an additional version of a custom toolbox without overwriting any of the other
installed versions, use the matlab.addons.install function and specify 'add' as the
installation option. For example, matlab.addons.install('C:\myAddons\GUI
Layout Toolbox 2.1.2.mltbx','add').
To select which version of the toolbox is enabled, go to the Home tab and select
AddOns > Manage Add-Ons. Click the button to the right of the toolbox you want. Then in
the Versions menu, select from the available versions. Selecting a version enables that
version and disables all other installed versions of the toolbox. You also can use the
matlab.addons.enableAddon function.
Add-On Manager: Save add-ons to new default location
MATLAB now saves add-ons to a new default location. The default location is platformspecific.
• Windows platforms — C:\Users\username\AppData\Roaming\MathWorks
\MATLAB Add-Ons.
• Linux platforms — ~/MATLAB Add-Ons.
• Mac platforms — ~/Library/Application Support/MathWorks/MATLAB AddOns.
3-4
Desktop
For more information, see Manage Your Add-Ons.
Documentation: View MATLAB documentation in Spanish
A subset of MATLAB documentation in Spanish is available on the web to licensed
MATLAB users. For more information, see Translated Documentation.
3-5
R2018b
Language and Programming
string Arrays: Use string arrays in MATLAB, Simulink, and
Stateflow
Specify text as string arrays where you previously specified text as character vectors or
cell arrays of character vectors. Use string arrays for data, properties, and name-value
pair arguments. Specify strings using double quotes, just as you specify character vectors
using single quotes.
For more information on string arrays, see Characters and Strings. For guidelines on
accepting strings in your own code, see Update Your Code to Accept Strings.
MathWorks® encourages the use of string arrays. For backward compatibility, MathWorks
products will continue to support the use of character vectors and cell arrays of character
vectors.
convertContainedStringsToChars Function: Convert string
arrays at any level of cell array or structure
To make your existing code accept string arrays, or cell arrays and structure arrays that
contain strings, use the convertContainedStringsToChars function on the entire
input argument list. For more information on accepting strings in your own code, see
Update Your Code to Accept Strings.
Enumerations: Improved performance of set operations with
enumerations
When called with enumeration arrays, execution of set operation functions such as
ismember is faster.
WSDL Web Services Documents: Required Tools Update
As of MATLAB R2018b, the supported versions of the Oracle® Java JDK™ and the
Apache™ CXF programs that are required to use a WSDL Web service in MATLAB have
changed.
For more informations, see Set Up WSDL Tools.
3-6
Language and Programming
Compatibility Considerations
Download and install the JDK software from the Java SE Downloads Web page https://
www.oracle.com/technetwork/java/javase/downloads. Choose the Java SE Development
Kit 8.
Download the latest version 3.2 release of the Apache CXF tool from https://
cxf.apache.org/download.
Functionality being removed or changed
validateattributes check for 'finite' and 'nonnan' attributes
Behavior change in future release
In the validateattributes function, the 'finite' and 'nonnan' attributes no
longer require that the input passes an isnumeric check.
Folders named resources will not be allowed on the MATLAB path
Still runs
In future releases, the resources folder will become a reserved folder, and folders with
the name resources will not be allowed on the MATLAB path. Currently, these folders
are allowed on the MATLAB path.
If a folder named resources is specified when calling the addpath, userpath, or
pathdef functions, MATLAB will return a warning and the folder will not be not added to
the path.
Rename all folders on the path named resources.
3-7
R2018b
Mathematics
boundaryshape Function: Create a polyshape object from a 2D triangulation
You now can use the boundaryshape function to convert a 2-D triangulation object
to a polyshape object.
polyshape Objects: Specify when to keep collinear points
when creating a polyshape
When creating a polyshape object, collinear points are removed by default. These
functions now offer the option to keep collinear points as vertices of the returned
polyshape using the name-value pair 'KeepCollinearPoints'.
polyshape
subtract
addboundary
union
intersect
xor
simplify
RandStream Objects: Generate random numbers using
Threefry and Philox algorithms
When creating a random stream with RandStream, you now can use the Threefry and
Philox random number generation algorithms.
GraphPlot Object: Customize node and edge labels with font
properties
GraphPlot objects have several new properties to enable customization of node and
edge labels in plots of directed or undirected graphs.
Compatibility Considerations
The new GraphPlot property Interpreter has a default value of 'tex'. In previous
releases, graph node and edge labels displayed text as the literal characters instead of
interpreting the text using TeX markup. If you do not want node and edge labels to use
TeX markup, then set the Interpreter property to 'none'.
sinpi and cospi Functions: Compute the sine and cosine of
multiples of π
The sinpi and cospi functions compute the values of sin(πx) and cos(πx). The answers
provided by these functions are more accurate than answers provided by sin(pi*x) or
cos(pi*x) because they do not compute pi*x explicitly. This convention compensates
for roundoff error in the floating-point value of pi.
3-9
R2018b
Graphics
Axes Interactions: Explore data with panning, zooming, data
tips, and 3-D rotation enabled by default
Interactively explore your data using axes interactions that are enabled by default. For
example, you can use the scroll-wheel to zoom into your data or hover over a data point to
see a data tip. Also, you can click and drag the axes to pan the axes (2-D view) or rotate
the axes (3-D view). For more information, see Interactively Explore Plotted Data.
Compatibility Considerations
In previous releases, none of the interactions were enabled by default. To control if the
axes interactions are enabled by default, use the disableDefaultInteractivity and
enableDefaultInteractivity functions.
Axes Toolbar: Access and customize a data exploration
toolbar for each Axes object
Axes have a toolbar that appears above the top-right corner for quick access to the data
exploration tools. The buttons available in the toolbar depend on the contents of the axes.
The toolbar typically includes buttons to brush data, add data tips, rotate the axes (3-D
axes only), pan or zoom the data, and restore the view.
You can customize the buttons available in the toolbar using the axtoolbar and
axtoolbarbtn functions.
Compatibility Considerations
In previous releases, the buttons that now appear in the axes toolbar appeared in the
figure toolbar instead. You can turn off the axes toolbar by setting the Visible property
of the AxesToolbar object to 'off'.
ax = gca;
ax.Toolbar.Visible = 'off';
3-10
Graphics
You can restore the figure toolbar buttons using the addToolbarExplorationButtons
command.
Geographic Plots: Create line, scatter, and point density plots
on interactive maps and control properties of a geographic
axes
Create line, scatter, and point density plots on interactive maps and control properties of
a geographic axes. Use the geoplot, geoscatter, and geodensityplot functions to
create these plots. The geolimits function now works with any of these geographic
plots, in addition to geographic bubble charts. To change the basemap used by any of
these geographic plots or charts, use the new geobasemap function.
stackedplot Function: Plot variables of a table or timetable for
comparison using a common x-axis
Plot the variables of a table or timetable. To ease visual comparison, the stackedplot
function provides a common x-axis and separate y-axes for the variables.
scatterhistogram Function: Visualize grouped data as a
scatter plot with marginal histograms
To create a scatter plot with marginal histograms, use the scatterhistogram function.
To group the data, you can use either the 'GroupVariable' name-value pair argument
with tabular data or the 'GroupData' name-value pair argument with arrays.
sgtitle Function: Create a title for a grid of subplots
You can add an overall title to a grid of subplots, in addition to adding a title to each
individual subplot. To add an overall title, use the sgtitle function.
3-11
R2018b
xline and yline Functions: Add vertical or horizontal lines to a
plot
To add vertical or horizontal lines to a plot, use the xline or yline functions,
respectively. For example, xline(3) plots a vertical line at x = 3.
3-12
Graphics
imtile Function: Combine multiple image frames into one
rectangular tiled image
To combine multiple image frames into one rectangular tiled image, use the imtile
function.
Data Tips: Use TeX or LaTeX markup in data tips with
improved visual appearance
Data tips have an improved visual appearance with new text colors.
Also, data tips now display text characters using TeX markup by default. Control the
interpretation of the text characters using the Interpreter property of the data cursor
mode object. Set the property value to 'tex' for TeX markup (default), 'latex' for
LaTeX markup, or 'none' for literal characters.
Compatibility Considerations
In previous releases, data tips displayed text as the literal characters instead of
interpreting the text using TeX markup. If you do not want data tips to use TeX markup,
then set the Interpreter property to 'none'.
Functionality being removed or changed
legend function interprets argument as property name when property exists
Behavior change
Starting in R2018b, if you pass an argument to the legend function that matches the
name of a legend property, the function interprets the argument as the name of a namevalue pair. In previous releases, the legend function recognized name-value pairs only
when the first argument was a cell array.
As a result of this change, in most cases, it is unnecessary to specify the first argument as
a cell array when using name-value pairs. However, if you want a label in your legend that
matches the name of a legend property, such as Position or NumColumns, then you
must specify all the labels in a cell array. Otherwise, the legend function interprets the
argument as a name-value pair instead of a label.
Description
Recommended Code
legend({'Label1','NumColumns','Label3','Label4'}
If you want a label in your legend that
matches the name of a legend property,
such as 'NumColumns', then specify all the
labels in a cell array. If you specify
'NumColumns' outside of a cell array, the
legend function interprets it as a namevalue pair.
If none of your labels match the name of a
legend property, then you do not need to
use a cell array around the labels.
legend('Label1','Label2','Label2')
alpha and shading set both FaceColor and FaceAlpha properties
Behavior change
3-14
Graphics
When updating surface and patch objects, the alpha and shading functions sometimes
set both the FaceColor and FaceAlpha properties. These functions set both properties
in cases where setting just one property results in a rendering issue. No updates to your
code are required.
In previous releases, the alpha function set only the FaceAlpha property. Similarly, the
shading function set only the FaceColor property.
3-15
R2018b
Data Import and Export
Import Tool: Generate improved code when importing from
spreadsheets
The Import Tool now offers improved code generation functionality for importing
spreadsheets across platforms. For example, you can import datetimes on Mac and Linux
and generate code that is easy to read. For more information, see Read Spreadsheet Data
Using Import Tool.
Compatibility Considerations
For more information, see “Import Tool handling of spreadsheet dates and times and
fields that are empty, unimportable, or error causing” on page 3-18.
Web-Based Data: Read from web-based data sources like
Amazon Web Services and Azure Blob Storage using
readtable, detectImportOptions, spreadsheetDatastore,
imread, and imfinfo
You can access tabular data and images from files stored in remote locations (Amazon S3,
Windows Azure® Blob Service, and HDFS™) using these functions:
• readtable
• detectImportOptions
• spreadsheetDatastore
• imread
• imfinfo
When reading data from remote locations, you must specify the full path using a uniform
resource locator (URL). For example, read a csv file from Amazon S3 cloud:
T = readtable('s3://bucketname/path_to_file/my_text_file.csv');
For more information on setting up MATLAB to access your online storage service, see
Work with Remote Data.
3-16
Data Import and Export
write Function: Write tall arrays in a variety of formats to
local or remote locations
The functionality of write is expanded to support additional formats and storage
locations:
• Output formats include .txt, .csv, .xls, and more.
• Name-value pairs to control format-specific options, such as WriteVariableNames
and Delimiter.
• Extended support for writing .seq and .mat formats to all supported file systems.
• Write data to remote locations in Amazon S3 or Windows Azure Blob Storage
(WASBS).
stlread and stlwrite Functions: Read from and write to STL
(Stereolithography) files for triangulations
The stlread function enables you to read triangulation information from an STL file to
create a triangulation object. You also can write a triangulation object or a 2-D
delaunayTriangulation object to a binary STL file with stlwrite.
TabularTextDatastore Object: Import data containing dates
and times from non-English locales
The TabularTextDatastore object now supports import of date and time data from
non-English locales. For example, to create a datastore for reading files that contain
German date and time data, set the DatetimeLocale parameter to 'de_DE'.
ds = tabularTextDatastore('myDataFile.csv','DatetimeLocale','de_DE')
readtable and writetable Functions: Read or write
spreadsheet files without initiating Microsoft Excel for
Windows on Windows platforms
On Windows platforms, you can choose not to open an instance of Microsoft Excel when
reading or writing data from spreadsheet files. Set the 'UseExcel' parameter to one of
these values:
3-17
R2018b
• true — Open an instance of Microsoft Excel to read (or write) the file. This setting is
the default for Windows systems with Excel installed.
• false — Do not open an instance of Microsoft Excel to read (or write) the file. Using
this setting might cause the data to be written differently for files with live updates
like formula evaluation or plugins.
For more information, see readtable and writetable.
readtable Function: Manage the import of empty fields using
import options
You can manage empty fields in tabular data by using readtable along with import
options. Use the EmptyFieldRule of import options object to specify how readtable
handles empty fields. For more information, see setvaropts.
Scientific File Format Libraries: CFITSIO Library upgraded to
version 3.420
The CFITSIO library is upgraded to version 3.420.
Functionality being removed or changed
Import Tool handling of spreadsheet dates and times and fields that are empty,
unimportable, or error causing
Behavior change
Starting in R2018b, the Import Tool app has improved functionality for importing data
from spreadsheet files. The changes to imported data are minimal and are limited to
uncommon cases:
• Empty or unimportable cells in spreadsheets:
• The value you use to replace empty cells and unimportable cells must be the same.
Previously, Import Tool allowed for different values for empty cells and
unimportable cells.
• Previously, Import Tool allowed you to specify a target string for cells that are
unimportable. This feature is no longer supported.
• Date and time data in spreadsheets:
3-18
Data Import and Export
• Import date and time data as MATLAB datetime arrays on all platforms.
• Import numbers as date and times on all platforms.
• Import Excel dates as numbers on all platforms.
• When running the Import Tool app in MATLAB on a Windows machine, cells in Excel
spreadsheets with error conditions are no longer displayed.
Basic parameter of the readtable function (Not Recommended)
Still runs
The Basic parameter of the readtable function is not recommended. Use the
parameter name UseExcel instead. There are no plans to remove the Basic parameter
at this time.
UseExcel parameter of the readtable and writetable functions
Behavior change in future release
In future releases, the default value of the UseExcel parameter will be changed to
false. The current default setting for UseExcel on Windows systems with Excel
installed is true.
This table shows the typical usage of readtable and how to update your code to
preserve the current behavior in future releases.
Code
0 comentarios
La pregunta está cerrada.
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!