https://in.mathworks.com/matlabcentral/answers/questionsMATLAB Answers — New Questions2021-01-26T06:44:51Ztag:in.mathworks.com,2005:Question/7218942021-01-20T09:02:04Z2021-01-26T06:43:29ZIs it possible to get some repeated values of non-dominated solutions in a pareto optimal solution set?I tried to solve an unconstrained multi-objective problem through a Non- Dominated Sort Evolutionary Algorithm (NDSEA) and got some repeated values of non-dominated solutions in the pareto optimal solutions set. I am now confused about the repeated values of non-dominated solutions in the optimal data set of solutions. Is it alright to have some repeated non-dominated solutions in the pareto optimal solution set? First 10 solutions of my pareto optimal solution set are attached in the screenshot file.
Please help me to clear the confusion that i have.
Syed Shahedhttps://in.mathworks.com/matlabcentral/profile/authors/17320433tag:in.mathworks.com,2005:Question/6670182020-11-28T21:22:02Z2021-01-26T06:43:18Zhow to make an array with the constellation point of qamqam_modulated_data = qammod(data_source, M); %where =8
now output will be points. How to insert those point in a array ?
please help me by writing the proper code,Dipsikha Royhttps://in.mathworks.com/matlabcentral/profile/authors/20445466tag:in.mathworks.com,2005:Question/970742010-01-22T16:45:00Z2021-01-26T06:27:50ZHow do I solve an ODE with time-dependent parameters in MATLAB?Consider the following ODE with time-dependent parameters:
y'(t) + f(t)y(t) = g(t)
and the given initial condition:
y(0) = 1
This is an example of an ODE with time-dependent terms. Suppose the time-dependent terms are defined only through the set of data points given in two vectors. Which of the MATLAB ODE solvers should I use, and how do I set up this problem?MathWorks Support Teamhttps://in.mathworks.com/matlabcentral/profile/authors/4622813tag:in.mathworks.com,2005:Question/7268632021-01-25T21:36:32Z2021-01-26T06:44:51ZExplanation of the following eval expressionHello everyone,
I am trying to understand how these two lines below works. Would appreciate if someone could help.
eval(['cd(''',filePath,''')'])
&
eval(['cd(''',cdold,''')']);
These two lines are taken from the following code:
...
cdold = cd;
[file, filePath] = uigetfile('lkDAT*.m','Please select a file');
eval(['cd(''',filePath,''')']); data = strtok(file,'.');
[LNK, dist, CSA, VNL, VNCalc, tn] = feval(data);
fprintf( '\nRead data from m-file %s',data);
eval(['cd(''',cdold,''')']);
fd=fopen(outputFile,'wt');
fprintf(fd,'\n*** %s - line parameters ***', outputFile);
fprintf(fd,'\n Date: %5d-%2d-%2d hour. %2d, %2dmin, %2.0fs',clock);
fprintf(fd,'\nRead data from m-file: %s', data);
...
Thanks.Jacek Sorokohttps://in.mathworks.com/matlabcentral/profile/authors/10236011tag:in.mathworks.com,2005:Question/7264832021-01-25T13:54:50Z2021-01-26T05:59:08ZHow to find what percentage of image an object coversFrom the given image, how can i find the percentage of cells covers the image or in other words What percentage of cell covers that image or What is the percentage of foreground image?
Elysi Cochinhttps://in.mathworks.com/matlabcentral/profile/authors/3625227tag:in.mathworks.com,2005:Question/7270382021-01-26T05:00:06Z2021-01-26T05:57:03ZLoading data from structure, using variableHI
I have loaded a structure format, and in this format, I want to load the y values
What I want to do is to load these structures, not by typing all of them individually, but using for loop
For example,
freq=2048;
DOF=3;
Force={'1','5','10','30'};
Axis={'x','y','z'};
CAxis={'X','Y','Z'};
Spacer={'','Sp_'};
SUBA = zeros(freq*2+1,DOF,DOF);
for i=1:DOF
for j=1:DOF
load(strcat('SUB_A5_A1_',string(Axis(1)),'_',string(Axis(1))));
var=sprintf(strcat('FRF_A_5__',string(CAxis{i}),'_A_1__',string(CAxis{j})));
SUBA(:,i,j)=var.y_values.values(1,:);
end
end
So for each loading structure, their name is like SUB_A5_A1_x_x or SUB_A5_A1_y_y etc...
For each structure, there is one more structure named like FRF_A_5__X_A_1__X or FRF_A_5__Y_A_1__Y etc... (Let's call them 'insidestructure')
I don't want to make all the lines for them, so I first thought using a variable 'var' for naming these 'insidestructure'. However, this didn't work. How can I treat this?
Thanks a lot준영 오https://in.mathworks.com/matlabcentral/profile/authors/19132266tag:in.mathworks.com,2005:Question/7263632021-01-25T11:59:49Z2021-01-26T05:56:58Zdo we have relation between LommelS2 and MeijerG in matlab?Do we have matlab relation between two special function "LommelS2 and MeijerG"?
How to convert LommelS2 code into MeijerG?
Please help !!
gourav pandeyhttps://in.mathworks.com/matlabcentral/profile/authors/14134751tag:in.mathworks.com,2005:Question/7270582021-01-26T05:56:36Z2021-01-26T05:56:36ZInvalid training data. The output size (11) of the last layer does not match the number of classes (1).I want to build seven inputs, one output network. (11 classes; 1, 2, ... , 11)
I used the filedatastore and tranformed datastore type.
My CNN model's input layer is 3D image arrays for each input.
One single mat file inculded Cell array (11x8); (7 double arrays (inputs) and categorical type (label))
{10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {[1 ]}
{10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {[2 ]}
{10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {[3 ]}
{10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {[4 ]}
{10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {[5 ]}
{10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {[6 ]}
{10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {[7 ]}
{10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {[8 ]}
{10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {[9 ]}
{10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {[10]}
{10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {10×9×640 double} {[11]}
When I load the datastore, I used below code.
TrainDS=Simple_combined([File_path 'Train']);
function [trainingDatastore]=Simple_combined(folder)
tempdatastore = datastore(folder,'ReadFcn',@load,'IncludeSubfolders',1,'Type','file','FileExtensions','.mat');
trainingDatastore = transform(tempdatastore,@rearrangeData);
function out = rearrangeData(ds)
out = ds.CombinedCell;
end
end
I tried to train my model using this code.
[trainedNet, traininfo]= trainNetwork(TrainDS,lgraph,options);
The error message was this: Invalid training data. The output size (11) of the last layer does not match the number of classes (1).
I also debuged the code.
I found the "ResponseSize" and "OutputSizes" are different after "iCreateMISOTrainingDataDispatcher" in the "trainNetwork" function.
trainingDispatcher =
GeneralDatastoreDispatcher with properties:
ImageSize: {[10 9 640 1] [10 9 640 1] [10 9 640 1] [10 9 640 1] [10 9 640 1] [10 9 640 1] [10 9 640 1]}
ResponseSize: {[1 1 1 1]}
NumObservations: Inf
ResponseMetaData: [1×1 nnet.internal.cnn.response.ClassificationMetaData]
IsDone: 0
Precision: [1×1 nnet.internal.cnn.util.Precision]
EndOfEpoch: 'discardLast'
ShuffleOption: 'once'
MiniBatchSize: 10
DataLoader: [1×1 nnet.internal.cnn.DataLoader]
DataTranslator: [1×1 nnet.internal.cnn.util.DataTranslator]
CollateFunctions: [1×1 struct]
InputSizes: {[10 9 640 1] [10 9 640 1] [10 9 640 1] [10 9 640 1] [10 9 640 1] [10 9 640 1] [10 9 640 1]}
OutputSizes: {[1 1 1 11]}
UnpackCellInputOutput: 0
CanPreserveOrder: 0
CatAndSliceStrategy: [1×1 nnet.internal.cnn.util.NDArrayCatAndSliceStrategy]
RunInBackground: 0
What should I do? Please help meYoungmin Nahttps://in.mathworks.com/matlabcentral/profile/authors/6400053tag:in.mathworks.com,2005:Question/7269632021-01-26T01:34:26Z2021-01-26T05:50:58ZI need help in splitting an arrayThe array I have-
A=[ 2 3 , 4 5 , 8 12 , 5 6 ]
The output I need-
C= [ 2 3 , 4 5 ]
D= [ 8 12 , 5 6 ]Sikder Meaghihttps://in.mathworks.com/matlabcentral/profile/authors/21256494tag:in.mathworks.com,2005:Question/7270482021-01-26T05:18:31Z2021-01-26T05:45:37ZOptimization issue, always different results?Hello everyone,
I'm trying to optimize a set of 3 parameters by using the following function:
options=optimset('Algorithm','levenberg-Marquardt', 'LargeScale','off', 'DiffMaxChange',0.01, 'DiffMinChange',0.0001, 'TolFun',1e-5, 'TolX',0.001);
[x,resnorm,residual,exitflag,output,lambda,jacobian]=lsqnonlin(@HSfun,x0,lb,ub,options);
At the end of the script, the function is reduced to a subtraction of vectors, so I do not consider important to post the whole script here. Input data is brought to the script from excel, and that's it. 3 parameters are optimized until reaching one of the optimization stopping criteria.
Altought I utilize Trust Reflective Region (default optimization Algorithm) instead of levenberg-Marquardt, the results of the optimization are always different for the same input data. And the results are sometimes more accurate than others.
My question is: Is this normal? These functions give you always different parameters answers even if the input data to optimize is the same?
Thanks in advance!Daniel Valenciahttps://in.mathworks.com/matlabcentral/profile/authors/19385420tag:in.mathworks.com,2005:Question/4758042019-08-12T10:37:06Z2021-01-26T05:41:34ZGet next or prior single precision value MATLAB function ?Is there a MATLAB function for next or prior float32 number ?
(similar to nextafterf, nexttowardf or float_next, float_prior)
tried these functions:
function [out] = next_SP(val)
% Get next after SP value - float32, single precision
% Increment float with smalllest step, SP representable
% TODO check for sign changes, domain INF NAN subnormals changes,
% uint32 ovf realmax + 1, mantissa exp changes
% Check nextafterf from math.h
% The nextafter() functions return the next representable floating-point
% value following x in the direction of y. If y is less than x, these
% functions will return the largest representable number less than x.
% If x equals y, the functions return y.
% https://www.boost.org/doc/libs/1_46_1/libs/math/doc/sf_and_dist/html/math_toolkit/utils/next_float/float_next.html
% Returns the next representable value which is greater than x.
% If x is non-finite then returns the result of a domain_error.
% If there is no such value greater than x then returns an overflow_error.
int_v = typecast(single(val), 'uint32' );
%disp([ 'Init ' num2str(single(val)) ' 0x' num2hex(single(val)) ', ' dec2bin(int_v, 32) ]);
int_v = int_v + 1;
out = typecast(uint32(int_v), 'single' );
%disp([ 'Init ' num2str(out) ' 0x' num2hex(out) ', ' dec2bin(int_v, 32) ]);
end
and
function [out] = prior_SP(val)
% Get next before SP value - float32, single precision
% Decrement float with smalllest step, SP representable
% TODO check for sign changes, domain INF NAN subnormals changes,
% uint32 udf realmax + 1, mantissa exp changes
% Check nexttowardf from math.h
% https://www.boost.org/doc/libs/1_48_0/libs/math/doc/sf_and_dist/html/math_toolkit/utils/next_float/float_prior.html
% Returns the next representable value which is less than x.
% If x is non-finite then returns the result of a domain_error.
% If there is no such value less than x then returns an overflow_error.
int_v = typecast(single(val), 'uint32' );
%disp([ 'Init ' num2str(single(val)) ' 0x' num2hex(single(val)) ', ' dec2bin(int_v, 32) ]);
int_v = int_v - 1;
out = typecast(uint32(int_v), 'single' );
%disp([ 'Init ' num2str(out) ' 0x' num2hex(out) ', ' dec2bin(int_v, 32) ]);
end
nexttoward_SP(-0)
Init 0 0x80000000, 10000000000000000000000000000000
Init NaN 0x7fffffff, 01111111111111111111111111111111
nexttoward_SP(0)
Init 0 0x00000000, 00000000000000000000000000000000
Init 0 0x00000000, 00000000000000000000000000000000
nexttoward_SP(-inf)
Init -Inf 0xff800000, 11111111100000000000000000000000
Init -3.402823466385289e+38 0xff7fffff, 11111111011111111111111111111111
nexttoward_SP(Inf)
Init Inf 0x7f800000, 01111111100000000000000000000000
Init 3.402823466385289e+38 0x7f7fffff, 01111111011111111111111111111111
nexttoward_SP(nan)
Init NaN 0xffc00000, 11111111110000000000000000000000
Init NaN 0xffbfffff, 11111111101111111111111111111111
(maybe similar for half or double precision)
Firan Lucianhttps://in.mathworks.com/matlabcentral/profile/authors/11849913tag:in.mathworks.com,2005:Question/7241932021-01-22T14:56:24Z2021-01-26T05:37:27ZEnding while loop with an input from the userGuys as i beginner at coding, i need help with ending while loop when the user type 'q'. My codes are below.
I appreciate your help. Thanks!
clc
clear
syms q
syms a
while a ~= 'q'
a = input('Lutfen tam bolenlerini bulmak istediginiz sayiyi giriniz:')
disp('cikmak icin q tusuna basin.')
tam_bolenler = tambolenler (a)
end
function tambo = tambolenler (a)
if a > 0
y = 1;
tambo(1,y) = [0];
for i=1:a
if (mod(a,i)==0)
tambo(1,y) = i;
y = y+1;
end
end
elseif a < 0
y = 1;
tambo(1,y) = [0];
for i=-a:-1:a
if (mod(a,i)==0)
tambo(1,y) = i;
y = y+1;
end
end
else a==0
print("Bu program 0 degeri icin sonuc vermez...")
end
endHani Kerem TURKOGLUhttps://in.mathworks.com/matlabcentral/profile/authors/20818704tag:in.mathworks.com,2005:Question/7264282021-01-25T13:02:07Z2021-01-26T05:17:53ZUnable to resolve the name results.NodalSolution.I am using R2020b. While solving a PDE with myufunction for updating the boundary condition at each iteration, I keep getting the error message 'Unable to resolve the name results.NodalSolution'. Any help is welcome.Shreya Georgehttps://in.mathworks.com/matlabcentral/profile/authors/16185186tag:in.mathworks.com,2005:Question/7269932021-01-26T02:50:05Z2021-01-26T05:16:02ZPassing individual elements of an array into a functionSay I have a function 'myfun' that takes n inputs: i.e. myfun(x1, x2, ... xn).
I have an array 'arr' that has n elements: i.e. arr = [ y1, y2, ... yn ].
I want to pass in y1, y2 ... yn as the input to myfun without typing myfun( arr(1), arr(2), ... arr(n) ). Is there a compact way of doing this?
If I type in myfun( arr(1:end) ) for example, x1 = arr and x2 ... xn are left unassigned,
but I want x1 = arr(1) = y1, x2 = arr(2) = y2 ... xn = arr(n) = yn.William Hewletthttps://in.mathworks.com/matlabcentral/profile/authors/6847998tag:in.mathworks.com,2005:Question/7270432021-01-26T05:04:42Z2021-01-26T05:08:26ZIndex in position 2 exceeds array bounds (must not exceed 1).gcf;
subplot(3,1,1)
plot(Y(:,1),Y(:,2))
title('source current')
ylabel('iS in A')
subplot(3,1,2)
plot(Y(:,1),Y(:,3))
title('capacitor voltage')
ylabel('vC in V')
subplot(3,1,3)
plot(Y(:,1),Y(:,4))
title('inductor current')
xlabel('time in sec.')
ylabel('iL in A')
Index in position 2 exceeds array bounds (must not exceed 1).
Error in (line 3)
plot(Y(:,1),Y(:,2))
LAKSHMAN SAhttps://in.mathworks.com/matlabcentral/profile/authors/13552663tag:in.mathworks.com,2005:Question/7269532021-01-26T00:54:21Z2021-01-26T05:02:49ZIs there a limit to the number of elements in an array in MatlabI have a binary file that comprises 16,814,160 bytes of 16-bit data in little endian format. I wish to open the file in Matlab and convert the 16-bit values to decimal in a 1 x 8407080 array. The first 8 bytes of the file in hex are: E0 0B 23 0C AD 0B 23 0C.
When I edit the file so that it comprises only the first 8 bytes, and then run the commands below, it returns [3040,3107,2989,3107] in the Workspace. This is as I would expect.
However, when I run the same program with all 16,814,160 bytes, the output is shown in the Workspace as a 1x4147200 double, of which the first four numbers are [56802,57570,56800,56801 and so on]. I would have expected the first four bytes to have remained unchanged!
Why is the array truncated to 4147200 elements and why have the decimal values been changed? The only difference is the input file size.
filename='my_binary_file(first_8_bytes).raw';
%filename='my_binary_file(all_bytes).raw' %uncomment this when reading in file size 16,814,160 bytes
fileID = fopen(filename, 'r', 'ieee-le'); % open the file for low level I/O function and obtain file identifier
if fileID == -1, error('Cannot open file: %s', filename); end
precision = 'uint16';
Data = fread(fileID, [1 8407080], precision); %reads data at byte level
fclose(fileID);
Thanks for your help.Steve Francishttps://in.mathworks.com/matlabcentral/profile/authors/21254876tag:in.mathworks.com,2005:Question/7269882021-01-26T02:47:51Z2021-01-26T04:52:35ZPrevent plot() filling missing data between pointsI have the plot belo where x=datenum and y=SPL. You can see, particularly in the second plot down, that there are periods where the data 'jumps'. This is because there are some missing days in the dataset. How do I leave these periods blank rather than having Matlab fill them in automatically? This is sound data so it is not correct to interpolate between the two points like this.
%all subplots use the same approach:
subplot(5,1,1)
X = [dBcalc_goat(:,1)' fliplr(dBcalc_goat(:,1)')];
Y = [dBcalc_goat(:,7)' fliplr(dBcalc_goat(:,10)')];
fill(X,Y,[0.929411764705882 0.694117647058824 0.125490196078431],...
'EdgeColor',[0.929411764705882 0.694117647058824 0.125490196078431]);
hold on
plot(dBcalc_goat(:,1),dBcalc_goat(:,5),'Color',[1 0 0],'LineWidth',2); %RMS level
plot(dBcalc_goat(:,1),dBcalc_goat(:,4),'Color',[ 0 0 0]); %median
plot(dBcalc_goat(:,1),dBcalc_goat(:,7),'Color',[0.929411764705882 0.694117647058824 0.125490196078431]); %5th percentile
plot(dBcalc_goat(:,1),dBcalc_goat(:,10),'Color',[0.929411764705882 0.694117647058824 0.125490196078431]); %95th percentile
xlim([first last]);
xticks([])
ylim([100 140])
xline(winter_19,'--');
xline(spring_19,'--');
xline(summer_20,'--');
xline(autumn_20,'--');
Louise Wilsonhttps://in.mathworks.com/matlabcentral/profile/authors/15959472tag:in.mathworks.com,2005:Question/7266532021-01-25T16:48:12Z2021-01-26T04:44:42ZCursors in uiaxes that is able to move horisontally along the x-axis according to mouseclicks by the user?Hi,
Is there any possibility to define a vertical line in uiaxes that is able to move horisontally along the x-axis according to mouseclicks by the user in an app?
I have a uiaxes plot in my app with time on the x-axis and I would like to have two cursors that enables the user to 'detect' the time difference between any points of interest...
Hoping for help.Laura Nielsenhttps://in.mathworks.com/matlabcentral/profile/authors/20340752tag:in.mathworks.com,2005:Question/7269432021-01-26T00:46:09Z2021-01-26T04:29:07ZCropping with image alignmentHi,
I am aligning a set of multiple photos using MATLAB's imregister(). In my set of images, the object grows in size (in the first image, the object is small, and as you go on through the images, the object becomes larger).
When aligning the images, some of the images are getting cropped. AKA the images are technically aligning properly, but when I display the image I see that the object of interest is cut off, not showing the entire object. It appears as though the image was translated downward and the image was cropped according to some kind of boundary.
Can I please have an answer as to why this is happening, and how I could potentially solve the cropping issue? I do not wish to share my code on the forum, just a general answer would be extremely helpful.
Attached is an example drawing to show what is happening.Ashlyn Kapinskihttps://in.mathworks.com/matlabcentral/profile/authors/15388318tag:in.mathworks.com,2005:Question/7257272021-01-24T17:02:53Z2021-01-26T04:25:55ZHow to find function and variable value at each iteration for genetic algorithm with Parallel Computing ?Hello everyone,
I have prepared code in matlab for genetic algorithm from toolbox for number of iteration (nit)
for i=1:nit
[x,fval,exitflag,output,population,score] = GAcode(nvars,lb,ub,InitialPopulationRange_Data,PopulationSize_Data,EliteCount_Data,CrossoverFraction_Data,MaxGenerations_Data,FunctionTolerance_Data,ConstraintTolerance_Data);
H1(i,1)=fval;
H2(i,1:nvars)=x;
end
where at the end H1 and H2 gives function and variable value for all the iterations respectively. 'GAcode' is file generated from toolbox. The code works properly.
I am trying to use parallel computing for increasing speed. Firstly started parallel pool and in preferences defined number of workers as 8. In file 'GA code' i have given
options = optimoptions(options,'UseParallel', true);
While using, parfor for i=1:nit, following error is obtained "Unable to classify the variable 'H2' in the body of the parfor-loop." If i remove H2 code runs properly.
How can i obtain H1 and H2 value after each iteration with parallel computing ?
For current setup even when the "for" loop for number of iterations is removed and done for single iteration no speed improvement is observed in parallel computing applying above options rather with parallel it is 63 sec and without it is 58 sec. The results are ok. What am i doing wrong ?
Thanks for your help.Ankur Shahhttps://in.mathworks.com/matlabcentral/profile/authors/14208584tag:in.mathworks.com,2005:Question/7270332021-01-26T04:15:17Z2021-01-26T04:15:17ZTo simulate the SIMULINK model on MATLAB I have been trying yo simulate the current SIMULINK block to a MATLAB program.
I got this result.
I have tried to simulate the same wave using MATLAB but I got the below results. I can't understand why for the similar integrators the simulated wave seems different. Is there any better way to to get the same simulink result on MATLAB??
clc;
clear all;
close all;
%Matlab program for a resonator
w=3; %Frequency in radians
Gain=-1; %Gain of the resonator
K1=1; %Gain of integrator 1
K2=1; %Gain of integrator 2
T=0.01; %Sample Time
%Define input and output of the resonator
n=0:T:20;
y1=zeros(1,length(n));
y2=zeros(1,length(n));
x1=zeros(1,length(n));
x2=zeros(1,length(n));
u1=zeros(1,length(n));
u2=zeros(1,length(n));
u1(1:length(n))=w*Gain;
x1(1)=1; x2(1)=0;
%y1(1)=1; y2(1)=0;
for i=1:1:length(n)
%Backward Euler method (Integrator 1)
for n1=1:1:length(n)
y1(n1)=x1(n1)+K1*T*u1(n1);
x1(n1+1)=y1(n1);
end
u2(1:length(n))=y1*w; %Input to Integrator 2
%Forward Euler method (Integrator 2)
for n2=1:1:length(n)
y2(n2)=x2(n2);
x2(n2+1)=x2(n2)+K2*T*u2(n2);
end
u1(1:length(n))=Gain*y2; %Input to Integrator 1
end
plot(n,y1,'ro',n,y2,'bo');
xlabel('Time(seconds)');
ylabel('Amplitude');
title('Sine and Cosine of the resonator');
legend('Integrator 1 (Backward Euler)','Integrator 2 (Forward Euler)');
grid on;Jerry Jacobhttps://in.mathworks.com/matlabcentral/profile/authors/18942340tag:in.mathworks.com,2005:Question/7247182021-01-23T06:37:12Z2021-01-26T04:14:18ZHow to fix this one? I use PI controller. please give a suggestion on this matter?Nyam Jargalsaikhanhttps://in.mathworks.com/matlabcentral/profile/authors/18514807tag:in.mathworks.com,2005:Question/7270282021-01-26T04:02:28Z2021-01-26T04:02:28ZSplit vector by value ranges?Given:
```w=[2,8,3,30,4,50,100,200,4,80,500]```
How can I turn the following into a single line of code?
```r=w(w>0 & w<10)
s=w(w>10 & w<100)
t=w(w>100 & w<1000)```
I tried variations of:
```[r,s,t]=w(w>0 & w<10),w(w>10 & w<100),w(w>100 & w<1000)```Don Kellyhttps://in.mathworks.com/matlabcentral/profile/authors/10998224tag:in.mathworks.com,2005:Question/7269832021-01-26T02:43:29Z2021-01-26T03:57:12ZHelp on plot 3 roots for each variable and connecting themI'm trying to plot the roots coming out of the this code but after I Run the code, no graph shows up. I know that for each variable K_p_no, there's 3 roots because the pol variable shows up in the Workspace with 3 roots in a single cell. How can I find the roots of the equation and plot them all in the same graph? If possible, also connect them. This is for a PID controller but without the ID, if it helps in any way.
clc; clear all; close all;
n = 10;
K_p_neg_inf = -1000;
K_p_pos_inf = 1000;
K_p_no = K_p_neg_inf:n:K_p_pos_inf;
for i=1:length(K_p_no);
ChEq{i} = [K_p_no(i)*50 K_p_no(i)*100 1 K_p_no(i)*60]; %characteris eqn (K_p*50*s^2 + K_p*100*s + s^2 + K_p*60) of the T_s, set =0 to find the poles in the s-plane
pol{i} = roots(ChEq{i}); %poles on s-plane
plot(real(poles), imag(poles), 'rx')
xlabel('Real Axis (seconds^-1)');
ylabel('Imaginary Axis (seconds^-1)')
grid on
endFranz Adam Magallaneshttps://in.mathworks.com/matlabcentral/profile/authors/18102256tag:in.mathworks.com,2005:Question/3844672018-01-24T05:00:00Z2021-01-26T03:56:39ZHow can I do integral from discrete data points?I have data "x" and "y" stored as arrays in MATLAB. How can I evaluate the area under the curve just from my data?
MathWorks Support Teamhttps://in.mathworks.com/matlabcentral/profile/authors/4622813tag:in.mathworks.com,2005:Question/5278182020-05-20T12:04:54Z2021-01-26T03:52:08ZLoad File Name for Simscape Multibody File Solid from WorkspaceIs there a way to specify the File Name parameter, that is, the file path of the geometry in the Simscape Multibody File Solid block with a MATLAB workspace variable?
It seems to me that only direct paths can be specified. Callbacks and masks are also only accessible to a limited extent. Does anyone have an idea how to implement this or is it just not possible?
Such a function would be very handy if you want to run simulations with different File Solids on one model.
I am grateful for any suggestion. mkohhttps://in.mathworks.com/matlabcentral/profile/authors/14661310tag:in.mathworks.com,2005:Question/7270182021-01-26T03:39:22Z2021-01-26T03:39:22ZMinimize banana function with steepest descent algorithmI write this code to minimize banana function but its not working.can any body help me please?
clear;clc;
banana=@ (x,y) (100*(y-x^2)^2+(1-x)^2);
x0=100;
y0=50;
dx=0.001;
dy=0.001;
error=0.0001;
g=[inf;inf];
number_of_iteration=0;
grad_x=@(x,y) (300*x^2-400*x*y+2*x-2);
grad_y=@(x,y) (200*(y-x^2));
banana0=banana(x0,y0);
grad_x0=grad_x(x0,y0);
grad_y0=grad_y(x0,y0);
while norm(g)>error
gx=grad_x(x0,y0);
gy=grad_y(x0,y0);
alpha_x=gx*dx;
alpha_y=gy*dy;
g=[gx;gy];
x0=x0-alpha_x;
y0=y0-alpha_y;
number_of_iteration=number_of_iteration+1;
end
fprintf('number of iterations until convergence is =%3i\n',(number_of_iteration));Mohamadmahdi Amirloohttps://in.mathworks.com/matlabcentral/profile/authors/21239457tag:in.mathworks.com,2005:Question/7259322021-01-25T02:00:14Z2021-01-26T03:34:40ZDid I wrongly add a source function to f Coefficient in PDE toolbox?Hello. I am practicing the tutorial of the PDE toolbox. Now I want to solve the wave equation. I created a 10m x 1m model, but I always fail to add the source function which is the f Coefficient. My fcoeffunction is below:
function f = fcoeffunction(location,state)
N = 1; % Number of equations
nr = length(location.x); % Number of columns
f = zeros(N,nr); % Allocate f
% Now the particular functional form of f
Nt_source=10;
dt=0.1;
source_time=Nt_source*dt;
wavelength=2;
source_f=1;
v=wavelength*source_f;
k=2*pi/wavelength;
for i=1:Nt_source;
f(1,1)=sin(k*(-v*dt*i))
end
end
as you can see, I want to create a source with frequency 1 Hz, wavelength 2m, speed 2m/s. I want to pulsed the source at x=1 in the model for 1 second long. All the y should have the same amplitude.
In the solver function, I made the simulation time for 2 seconds. each time step is 0.02s
n = 101;
tlist = linspace(0,2,n);
u0 = @(location) 0*(location.x);
ut0 = @(location) 0*(location.x);
setInitialConditions(model,u0,ut0);
specifyCoefficients(model,'m',1,'d',0,'c',4,'a',0,'f',@fcoeffunction);
applyBoundaryCondition(model,'dirichlet','Edge',1:4,'u',0);
So in theory, the wave should travel only 2 x 2= 4m as a nice sine wave and never reach the right boundary. However, the result shows something different. The wave never travel and there are two spikes at 4.4m and 7m. Why is that? Which part did I do wrong?
Y. Gaohttps://in.mathworks.com/matlabcentral/profile/authors/14509504tag:in.mathworks.com,2005:Question/1012732010-09-08T18:11:00Z2021-01-26T03:31:32ZHow can I put existing figures in different subplots in another figure in MATLAB 6.5 (R13)?I want to make several plots, each in their own figure. I then want to create a final figure which contains subplots which have the contents of the original figures.
MathWorks Support Teamhttps://in.mathworks.com/matlabcentral/profile/authors/4622813tag:in.mathworks.com,2005:Question/7270132021-01-26T03:30:34Z2021-01-26T03:30:34ZIssue implementing custom fully connected layer - weights converging to 0I'd like to implement a custimized version of the fully connected layer. Before that, I'd like to make sure I can replicate the default FullyConnectedLayer that comes with Matlab. While my implementation did not return errors, the weights the network learned were unusually small. In my simulation, the default FullyConnectedLayer returned weights mostly between [1,0]. My implementation returned weights around 0 (e.g., 10^-40). Can someone help explain why this is happening?
classdef CustomFCLayer < nnet.layer.Layer
% Custom fully connected layer, constrain weights to be positive.
properties (Learnable)
% Layer learnable parameters
Weights
Bias
end
methods
function layer = CustomFCLayer(prev_units,num_units,name,initWeights)
% layer = CustomFCLayer(numInputs,name) creates a
% fully connected layer
layer.Name = name;
layer.Description = 'Fully connected layer';
if ~exist('initWeights','var')
std = sqrt(2/(num_units+prev_units));
layer.Weights = std*rand([num_units prev_units]);
else
assert(size(initWeights,1)==num_units)
assert(size(initWeights,2)==prev_units)
layer.Weights = initWeights;
end
layer.Bias = zeros([num_units 1]);
end
function Z = predict(layer, X)
% Forward input data through the layer at prediction time and
% output the result
Z = (layer.Weights)*X+layer.Bias;
end
end
endKenny Chouhttps://in.mathworks.com/matlabcentral/profile/authors/7920344tag:in.mathworks.com,2005:Question/4633032019-05-21T15:03:50Z2021-01-26T03:27:36ZProblem installing add-onsIn MATLAB R2019a I try installing add-ons from the add-on manager. I am then notified that MATLAB will be closed and I click on continue. Once I do that I get windows asking me if I want to give permission to Matlab add-on to install files and I give it. However, after this nothing happens and the add-on doesn't get installed. Does anyone know why this might be the case?Simone Coppolahttps://in.mathworks.com/matlabcentral/profile/authors/10516419tag:in.mathworks.com,2005:Question/3606462017-10-10T18:26:12Z2021-01-26T03:27:20ZHow can i get a RGB values from a picture?Hi,
My goal is to get the RGB values of the image taken with the webcam and I need the matlab code to accomplish this purpose. I am a new matlab user, please help me.
Best regards.
caner kayahttps://in.mathworks.com/matlabcentral/profile/authors/11206577tag:in.mathworks.com,2005:Question/7270082021-01-26T03:13:13Z2021-01-26T03:22:54Zhow to do smoothen this graphthis is my coding.
f=5000;
C=[2.000 1.000 0.665 0.500 0.400];
Xc=[15 30 48 58 76];
%% a
data=C*10^-6*f
eq=1./data
%% b
figure
subplot(4,4,[(1,2);(5,6)])
p=polyfit(C,Xc,2)
f=polyval(p,C);
f2=p(1)*C.^2+p(2)*C+p(3)
plot(C,Xc,'o',C,f,'--')
axis([0 2 10 80]);
legend('Experiment Data','Polynomial Fitting', 'Location','northeast')
xlabel('C(\muF)')
ylabel('XC(\Omega)')
NURASYIFA ROSLIhttps://in.mathworks.com/matlabcentral/profile/authors/20103495tag:in.mathworks.com,2005:Question/5265972020-05-19T12:55:17Z2021-01-26T03:22:18ZWrite a function max_sum that takes v a row vector of numbers & n,a positive integer as inputs.The function needs to find n consecutive elements of v whose sum is largest possible.It returns summa & index of first element of n consecutive integers.
%Example-[summa,index]=max_sum([1 2 3 4 5 4 3 2 1],3)
% summa=13
% index=4
function [summa,index]=max_sum(v,n)
total=v(1,1);
if n>v
summa=0;
index=-1;
else
for ii=1:length(v)
jj=ii+(n-1);
if jj<=length(v);
total=[total,sum(v(ii):v(jj))];
end
[summa,index]=max(total);
end
endvidushi Chaudharyhttps://in.mathworks.com/matlabcentral/profile/authors/18413210tag:in.mathworks.com,2005:Question/7191952021-01-17T12:45:36Z2021-01-26T03:16:13ZHow to find the inner distance between the 2 white linesHi,someone can give me a hand to make a script related to the problem?
Practically ,I want to get the distance column by column from the lowest white border of the upper part to the highest white border of the lower part.
I thank you in advance.
Francesco Muoiohttps://in.mathworks.com/matlabcentral/profile/authors/20420023tag:in.mathworks.com,2005:Question/7268982021-01-25T22:49:51Z2021-01-26T03:12:28ZQuestion about accessing data in a structHi all,
I am trying to get data from an xml file using xml2struct. currently, I am calling on the data using the syntax
DataSet.Children(x).Children(y).Children(z).Children.Data
where Dataset is my structure and x, y and z are integers referring to the index position. The problem is that sometimes the xml structure stores the same information in different positions meaning x, y and z will be different for these. For example, the "date" field might be the 3rd index (x=3) in one file, or the 2nd index (x=2) in another.
Is there a way to navigate around this please? I need to have a consistent way to gather this data because I loop through several xml files, so I need to get the same, consistent information from all the files with certainty.
I have tried to use "find" but to no avail.
Thank you in advanceTeshan Rezelhttps://in.mathworks.com/matlabcentral/profile/authors/17128181tag:in.mathworks.com,2005:Question/7270032021-01-26T03:07:13Z2021-01-26T03:07:13ZSupport Vector Machines for Regression problemsI am studying Machine learning in Coursera (by Andrew Ng) and I finished learning about Support Vector Machines (SVM). I read that SVM can also be used for regression problems (also called Support vector Regression or SVR) and I'm interested in learning it. I tried reading articles about but it doesn't work for me. I posted this question on our discussion forum but one of the mentors suggested that I should post this question here instead. Can someone provide a code for SVR that has live scripts similar with how programming assignments are done in Coursera? This approach really works for me. Thank you very much! Lea Caguiathttps://in.mathworks.com/matlabcentral/profile/authors/20155595tag:in.mathworks.com,2005:Question/7268782021-01-25T21:44:50Z2021-01-26T03:06:31ZFeedback command for MIMO systems in MATLABI have a state space model with 12 outputs and 4 inputs. I want to close the loop of 8th output with 3 input. then in outer loop i want to close outer loop for 1 output and 3 input again (Quadrotor Pitch and X position states). I have designed PD controller for both loops which is in feedforward.
states = {'x' 'y' 'z' 'u' 'v' 'w' 'Phi' 'Theta' 'Psi' 'p' 'q' 'r'};
inputs = {'Thrust' 'Roll Torque' 'Pitch Torque' 'Yaw Torque'};
outputs = {'x' 'y' 'z' 'u' 'v' 'w' 'Phi' 'Theta' 'Psi' 'p' 'q' 'r'};
STATE_SPACE_MODEL = ss(A,B,C,D,'statename',states,'inputname',inputs,'outputname',outputs);
Now, I can close the first inner loop this way
Pitch_State=STATE_SPACE_MODEL('Theta','Pitch Torque');
PITCH_CL=feedback(Pitch_State*P_PD,1);
now, i want to close the outer loop that contains 'x' state and have a seperate PD controller. I cant find out how to close the outer loop using feeback command can anyone help me out?Muhammad Adeel Ahsan Awanhttps://in.mathworks.com/matlabcentral/profile/authors/11630357tag:in.mathworks.com,2005:Question/7260582021-01-25T05:12:15Z2021-01-26T03:01:19ZHow can I merge my data set based on the time in MATLAB?I want to merge the two data into one. But as they are in two different times that's why I cannot just combine them.
I need to add them by keeping the time as it is. How can I do this?
data_1_y_axes=[0,1,3,5,4,6,8,9,7]
time_1_x_axes=[.02,0.03,.05,.06,.07,0.08,0.09,.1,.2]
data_2_y_axes=[0,2,4,5,2,7,5,7,5]
time_2_x_axes=[.002,0.004,.006,.009,.02,0.04,0.06,.07,.09]
plot(time_1_x_axes,data_1_y_axes)
hold on
plot(time_2_x_axes,data_2_y_axes)
My expected data will be as follows:
New_data=[ 0, 2,4,5,2+0,1,7,3,5+5,7+4,6,5+8,9,7]
New_time=[.002,.004,.006,.009,.02,.03,.04,.05,.06,.07,.08,.09,.1,.2]
How can I do this?
Tania Islamhttps://in.mathworks.com/matlabcentral/profile/authors/14515142tag:in.mathworks.com,2005:Question/7269732021-01-26T02:17:16Z2021-01-26T02:55:04ZAdding new inputs to trained networkI'd like to know how to test the network below on a new data point after the network is trained. For example
% Prepare training data, train and test network
X = tonndata(input,true,false);
T = tonndata(output,true,false);
net = narxnet(inputDelays,feedbackDelays,hiddenLayerSize,'open',trainFcn);
[x,xi,ai,t] = preparets(net,X,{},T);
[net,tr] = train(net,x,t,xi,ai);%'useParallel','yes')
y = net(x,xi,ai);
%new datapoint 'new_X ' appears after training the network, input new_X into trained net and generate new_y estimate (no retraining)
[???]
Data is time series. I looked at this https://www.mathworks.com/matlabcentral/answers/152177-how-to-use-narxnet-for-new-set-of-data but did not find it helpful. Also, the network is open, I'm not running a closed network so this seems N/A to my question: https://www.mathworks.com/help/deeplearning/ref/narxnet.html.
This seemed somewhat helpful https://towardsdatascience.com/building-a-narx-in-matlab-to-forecast-time-series-data-f60561864874, with this code snippet:
% Step-Ahead Prediction Network
% For some applications it helps to get the prediction a timestep early.
% The original network returns predicted y(t+1) at the same time it is
% given y(t+1). For some applications such as decision making, it would
% help to have predicted y(t+1) once y(t) is available, but before the
% actual y(t+1) occurs. The network can be made to return its output a
% timestep early by removing one delay so that its minimal tap delay is now
% 0 instead of 1. The new network returns the same outputs as the original
% network, but outputs are shifted left one timestep.
nets = removedelay(net);
nets.name = [net.name ' - Predict One Step Ahead'];
view(nets)
[xs,xis,ais,ts] = preparets(nets,X,{},T);
ys = nets(xs,xis,ais);
stepAheadPerformance = perform(nets,ts,ys);
But I dont see how to feed the new_X additional datapoint in? Do I append it to X?
Update_X=[X new_X];
%then run that through preparets? A code snippet would be helpful.
andohttps://in.mathworks.com/matlabcentral/profile/authors/274659tag:in.mathworks.com,2005:Question/7259072021-01-25T00:28:00Z2021-01-26T02:38:00ZHow do I find a D matrix that satisfies [K]*inv(M)*[D]==[D]*inv(M)*[K] ? M and K are respectively a mass and stiffness matrices 12x12, I need to find a matrix D 12x12 that satisfies this equality.
Thank you for your help ikram ros salamathttps://in.mathworks.com/matlabcentral/profile/authors/19930339tag:in.mathworks.com,2005:Question/7269682021-01-26T01:57:40Z2021-01-26T02:26:28ZExtract subsets of consecutive entries in a matrixI have an n x p matrix, A, of multivariate data. (n - data points, p - independent variables).
I want to select random subsets (i.e. extract collections of rows) from this data of size (p+1). The subsets need to be comprised of rows that are consecutive.
For example:
matrix = rand(100,4);
%n = 100, n data points
%p = 4, p independent variables
I want to create a random subset of 5 rows (p+1 = 5). So, rows 1 through 5 or 43 through 47, etc.
I know there are functions like randsample and datasample but I'm not sure how to use these to get subsets of rows that are together and not chosen at random throughout the matrix.Zavian Buchananhttps://in.mathworks.com/matlabcentral/profile/authors/11608008tag:in.mathworks.com,2005:Question/7267332021-01-25T17:58:20Z2021-01-26T02:23:03ZUndefined function or variable 'lgamma'.Hello experts,
as the title says I have a problem with this undefined 'lgamma'.
I'm trying to run an ANCOVA using the function aoctool() but it stops and throws me that error.
Below I post the entire message:
Undefined function or variable 'lgamma'.
Error in betapdf (line 60)
+ lgamma (a + b) - lgamma (a) - lgamma (b));
Error in betainv (line 87)
h = (betacdf (y_old, a, b) - x) ./ betapdf (y_old, a, b);
Error in finv (line 58)
inv(k) = ((1 ./ betainv (1 - x(k), n/2, m/2) - 1) * n / m);
Error in aoctool>getyvalues (line 777)
crit = sqrt(df1 * finv(1-alpha/bonf, df1, df2));
Error in aoctool (line 335)
[newy, ~, ycov] = getyvalues(allx, allgrps, model, stats, ud);
I'm working on MATLAB R2018b.
Is this related with a MATLAB issue or (most likely) it's just me erroneously defining the ANCOVA variables?
Thank you for your help!
MarcoMarco Ninghettohttps://in.mathworks.com/matlabcentral/profile/authors/16486959tag:in.mathworks.com,2005:Question/401062012-06-01T22:32:31Z2021-01-26T02:16:19Zcontourc - plotting contour matrixI would like to find the contours, manipulate them, and then plot them.
This plots contours
x = 0:0.1:1; y = 0:0.1:1;
[X,Y] = meshgrid(x,y);
Z = sin(X).*cos(Y);
[con_mat, h] = contour(x, y, Z);
To get the contour information without plotting, can use contourc.
con_mat = contourc(x, y, Z);
However, there appears to be no built-in way to plot this "contour matrix".
Any thoughts?
John
John Mahoneyhttps://in.mathworks.com/matlabcentral/profile/authors/3076592tag:in.mathworks.com,2005:Question/7252172021-01-23T21:21:00Z2021-01-26T02:16:10ZHow to do a Loop statement from cell to double?Hi there
I have a file with wind information (direction and speed), the wind direction has this format (E, N, NE,...) I would like to do a wind rose from 1989 to 2019, so I have a file.xls with multiple sheets (from 1989 to 2019). I'm trying to convert the wind direction from (E, N, NE to 90, 0 , 45). But I do not know how to do it, any help? I post the file (1989.xlsx) and what I've been doing.
%% I created a artificial data to organized wind speed and direction
t1 = datetime(1989,01,01,00,00,00);
t2 = datetime(2019,12,31,23,00,00);
t = (t1:hours(1):t2)';
% my idea is to convert ('E', 'N'... to 90, 0) to the 30 years.
for i = length(1989.VarName1(10:40))
if 1989.Dir{10:40},'E' == 1;
1989.Dir(10:40)= 90;
end
endFabian Morenohttps://in.mathworks.com/matlabcentral/profile/authors/18939934tag:in.mathworks.com,2005:Question/7254422021-01-24T10:07:42Z2021-01-26T02:11:39ZCloseRequestFcn of GUI not working with wrong current folderI have in the GUI m-file a 'figure1_CloseRequestFcn'. This works fine as long the current Matlab folder is not changed.
When I run another file from another folder, I cannot quit Matlab unless I make the GUI-folder to the current folder.
With the standard CloseRequestFcn in the GUI property I can allways quit Matlab, even if the current folder is not the GUI folder.
Is there a way to insert into the GUI-figure-property something like:
'try;MyGUI(''figure1_CloseRequestFcn'',hObject,eventdata,guidata(hObject));catch;closereq;end;' ?
I do not want to change anything like the search path in Matlab.Peter Seiboldhttps://in.mathworks.com/matlabcentral/profile/authors/2474090tag:in.mathworks.com,2005:Question/7243082021-01-22T16:33:25Z2021-01-26T02:01:33ZHelp with an ECG signalYou are provided with .wav file which contains a simulated electrocardiogram signal (ECG) with a low frequency (drift) signal, an interfering tone and white Gaussian noise added. Using MATLAB you will analyse this signal in the time and frequency domain to quantify the interference/noise. You will then design and implement digital filters to remove as much of the interference/noise as possible while preserving the underlying ECG signal.
Link to the noised ECG signal and desired output is given below:-
https://drive.google.com/drive/folders/12rrvzTg9nBdeMY-dp5IylfMwsmYgsztb?usp=sharing
Problem 1:-
First read the provided signal (ECG.wav) into MATLAB then plot and inspect the signal in the time domain, recording your observations on the nature of the interference. Next, view the signal in the frequency domain and extract the key parameters of interest e.g. the frequency of tonal interference and the level and spectral distribution of noise. These parameters are required for the filter design tasks to follow.
Problem 2:-
Design an infinite impulse response (IIR) highpass filter based on a 2nd order Butterworth prototype using the bilinear z-transform method. This should have a cut off frequency of 0.1 Hz to remove the low frequency drift on the signal. Verify the response of this filter in MATLAB and then apply to the ECG signal, observing the result in the time domain.
Problem 3:-
Using the impulse response truncation method, design a finite impulse response (FIR) lowpass filter with a passband edge at 10 Hz and at least 50 dB attenuation at the frequency of the tonal interference identified in problem 1. Verify the response of this filter, then apply this to the highpass filtered ECG signal and inspect the output signal in the time and frequency domain.
Problem 4:-
Increase the cut-off frequency of the FIR lowpass filter applied in problem 3 to 50 Hz to preserve more of the ECG signal spectrum. Now remove the tonal interference signal using an adaptive filter in the noise cancelling configuration (direct model) and compare the output signal with that produced in problem 3. (The reference interference signal may be obtained by generating a sine wave at the interference frequency identified in problem 1).
Problem 5:-
The ECG signal is significantly oversampled and hence the above operations could be carried with fewer operations by using a multirate DSP approach. Analyse the computations required to achieve the output of problem 3 and propose an alternative approach using a two stage filter to reduce computation. Verify that this produces a similar output with fewer computations and faster execution time in MATLAB.Abdullah Javedhttps://in.mathworks.com/matlabcentral/profile/authors/12839991tag:in.mathworks.com,2005:Question/7254272021-01-24T09:31:18Z2021-01-26T01:59:56ZGuess for fsolve returns similar answer (heavily non-linear equations)I have a huge function (36 variables) that I am solving using fsolve and the optimization options as shown in the code below:
fun=@BIGFunc
x0[1:33]=[ones]
x0[34:36]=[5, 5, 5]
options = optimoptions('fsolve','Algorithm','levenberg-marquardt',...
'Display','iter','FunctionTolerance',1e-15,'TolX',1e-15,'MaxFunctionEvaluations', 12000,'MaxIterations',600);
[x,fval,EXITFLAG,OUTPUT] = fsolve(fun,x0,options)
The guesses for the first 33 variables are variant (I put them 1s as of simplicity. When solving the function, the answers for the 34-36 variables are just below the provided guess. For example, with a guess of 5, I get 4.9, and for 7, I get 6.9, and so on. Is there something wrong here or is my function extremely non-linear, which exihbits multiple solutions and is very subjective to my initial guess?
I would appreciate your inputs.Omar Khalifahttps://in.mathworks.com/matlabcentral/profile/authors/20209544tag:in.mathworks.com,2005:Question/946562009-06-27T01:11:00Z2021-01-26T01:49:54ZWhy do I receive License Manager Error -2?When starting MATLAB, I receive the following error:
ERROR: License checkout failed. Invalid license file syntax. License Manager Error -2.
MathWorks Support Teamhttps://in.mathworks.com/matlabcentral/profile/authors/4622813tag:in.mathworks.com,2005:Question/7259372021-01-25T02:03:59Z2021-01-26T01:45:12ZHow to use toogle button to switch on and off a push button?when i push the toggle button, it displays on and off but I want that when I pressed the toggle switch to on, the "add" pushbutton will execute. I'm thinking of adding a while loop to the code of "add" button but i dont know how. I want my add button executes only when the toggle button is on.
here's my code:
% --- Executes on button press in add.
function add_Callback(hObject, eventdata, handles)
% hObject handle to add (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA);
persistent add
count=handles.count;
if isempty(add)
add=count;
add=add+1;
else
add=add+1;
end
handles.add=add;
set(handles.screen,'String',add);
guidata(hObject, handles);
% --- Executes on button press in on_offbutton.
function on_offbutton_Callback(hObject, eventdata, handles)
% hObject handle to on_offbutton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of on_offbutton
button_state = get(hObject,'Value');
if(button_state == 1)
set(handles.on_offbutton,'String','ON','ForegroundColor','green')
else
set(handles.on_offbutton,'string','OFF','foregroundcolor','red')
endSofia Venturahttps://in.mathworks.com/matlabcentral/profile/authors/21057365