https://la.mathworks.com/matlabcentral/answers/questionsMATLAB Answers — New Questions2019-06-17T11:15:25Ztag:la.mathworks.com,2005:Question/4674102019-06-17T07:38:18Z2019-06-17T11:15:25ZTrouble in replicating the resultsHello everyone
I'm new to this forum. I have been having some trouble in replicating the results of a partial differential equation in the series form (already published data). It seems that there is a computational error somewhere in the code because of which the results are diverging. I would be grateful if anyone could pitch in to help. I have attached the files you may need during the discourse which also includes the algortihm of the problem.
Best Regards
Zuhaib Nissarhttps://la.mathworks.com/matlabcentral/profile/authors/13143745-zuhaib-nissartag:la.mathworks.com,2005:Question/4670392019-06-14T07:28:26Z2019-06-17T11:14:34ZLinear indices from row and column indices for a rectangular region of interest.I have the row and column indices of a rectangular region of interest in a rectangular image. How can i get the linear indices from these row and column indices?
%this works
a = rand(5,5); %changed.
row_indices = 1:5;
col_indices = 1:5;
[X,Y] = meshgrid(row_indices,col_indices);
indices = sub2ind(size(a), Y, X)
%i want the indices when rows and cols are not necessarily of same length.
a = rand(5,3); %changed
row_indices = 1:5;
col_indices = 1:3;
[X,Y] = meshgrid(row_indices,col_indices);
indices = sub2ind(size(a), Y, X) %this would give out of range subscript.
bayesianguyhttps://la.mathworks.com/matlabcentral/profile/authors/13109923-bayesianguytag:la.mathworks.com,2005:Question/4674442019-06-17T11:13:17Z2019-06-17T11:13:17ZPlaying different audio files through different output channels of soundcardHi, I have the TASCAM US-16x08 soundcard having 8 output channels. How can I play 8 different music files from the computer through these 8 different output channels?Sudeep Surendranhttps://la.mathworks.com/matlabcentral/profile/authors/15316706-sudeep-surendrantag:la.mathworks.com,2005:Question/4674152019-06-17T08:07:15Z2019-06-17T11:12:58ZSave uijauge in a GUI
I created a GUI with many gauges and I would like to save them in png for a PDF. How can I do this?Adrien Vallaurihttps://la.mathworks.com/matlabcentral/profile/authors/14442160-adrien-vallauritag:la.mathworks.com,2005:Question/4674232019-06-17T09:20:06Z2019-06-17T11:11:39ZHow to use examples?After I copy the "openExample('wlan/DMGSCLinkWithRFBeamformingExample')" onto the Matlab, I cannot find the example. the error is
"Wrongly used findExample (line 35)
Cannot find "HTLinkModelWLANExample" in "D:\Matlab2018b\examples\wlan\examples.xml".
Error: openExample (line 24)
metadata = findExample(id);"
Qinghe Gaohttps://la.mathworks.com/matlabcentral/profile/authors/15269191-qinghe-gaotag:la.mathworks.com,2005:Question/4674252019-06-17T09:23:23Z2019-06-17T11:11:19Zwrong file sorting in imageDatastore.m
The image does not correspond to the filename of the real background.
Nico336https://la.mathworks.com/matlabcentral/profile/authors/9076366-nico336tag:la.mathworks.com,2005:Question/4674372019-06-17T10:35:46Z2019-06-17T11:09:48ZHow to fix the errors Arise from moving .m files and functions in folders?I wrote some codes in Matlab for classification and I achieved the desired results, all the functions which were used in the program exist in Matlab projects path in C drive in my computer but for running another clustering program in Matlab, I removed the .m files and functions from the Matlab's projects path and saved all of them as a folder in C drive.
Now my first program shows errors about some of these functions while It didn't have any problems with the function's codes before, even I returned files to the previous state but this problem still exists.
Should I put the required functions in the Matlab's projects path or in another folder?
I'll be grateful to have your opinions about how to fix these errors.phdcomputer Enghttps://la.mathworks.com/matlabcentral/profile/authors/12712473-phdcomputer-engtag:la.mathworks.com,2005:Question/3010552016-08-27T08:59:43Z2019-06-17T11:08:35ZHow to remove trailing zeros while display any floting number ? format short g;
X=input ('any>');
%if input is 93.93
disp (X);
It display 93.930
How to disp 93.93
I can't remove
format short g;
Bcz of another mathematical reasons and calculations...Kelvin Virojahttps://la.mathworks.com/matlabcentral/profile/authors/8519959-kelvin-virojatag:la.mathworks.com,2005:Question/4674392019-06-17T10:45:41Z2019-06-17T11:04:30ZSampling of the received signal vectors in matlabHow to calculate the sampling frequency from the received signal vectors?
If I have to sample the received signal (in GHz frequency) with new sampling frequency. how to calculate the new sampling frequency?Rajanish Bhairannawarhttps://la.mathworks.com/matlabcentral/profile/authors/3548985-rajanish-bhairannawartag:la.mathworks.com,2005:Question/4674432019-06-17T11:04:14Z2019-06-17T11:04:14Zperiod of time and cycling time in SimulinkHello,
I have a question related to the simulink model.
I would like to design a system which switches the signal output during 1 cycling time (10 ms).
It means that the input has connected to the block. Then I want to create a block calculation which detects the present of value in less than 10 ms. If the value is available in less than 10ms the switch connect to 1st condition and if after 10ms the input is still not available the switch connects to 2nd condition.
So it counts from the time that the value is not available until 10 ms, if it is still not available it takes actions to switch.
I have tried the block delay, but it takes action after 10 ms (sampling time Ts = 10ms). so it does not fit with objective.
Thank you!ma vannarahttps://la.mathworks.com/matlabcentral/profile/authors/6000525-ma-vannaratag:la.mathworks.com,2005:Question/4674422019-06-17T11:02:27Z2019-06-17T11:02:27Z I would like know if it is possible to make the graph look like the one I have printed below. I more interested in the code in matlab 2018a. Please kindly be a little explicit in your explanation. Thanks in anticipation of your favourable responses.Ezekiel Omoniyihttps://la.mathworks.com/matlabcentral/profile/authors/15657091-ezekiel-omoniyitag:la.mathworks.com,2005:Question/4674412019-06-17T10:59:15Z2019-06-17T11:00:25ZIs the parameter estimates reliable, if I get the error " Iteration limit exceeded in the Laplacian algorithm. Returning result of the final iteration"I use the nlme model with exponential error and FOCE method of likelihood estimation to fit the PK data. I got the highest loglikeihood with this setting. But I also got a error/warning that
"Iteration limit exceeded in the Laplacian algorithm. Returning result of the final iteration"
What should I do to overcome this error. Should I even try to overcome this.? With this error, if I try to report the parameter estimate is it authentic.?
I am also attaching the algorithm settings of iteration with this question for reference regarding my settings. Praveen Kumar Mhttps://la.mathworks.com/matlabcentral/profile/authors/8711788-praveen-kumar-mtag:la.mathworks.com,2005:Question/4672882019-06-16T03:23:25Z2019-06-17T10:54:31ZLog likelihood is initially high in FOCE but as the iteration proceeds to greater than 3500 the log likelihood reduces and finally ends with error that maximum iteration has been achieved.I am trying to develop a population pharmacokinetic model using Simbiology,
My settings are
Estimation method: Estimating mixed effects model with nlmefit
Error model is proportional
Method to approximate non-linear mixed effect model likelihood is FOCE.
The FOCE model fitting progress shows a loglikelihood of around -200 (that is good) till iteration of 3500 but after that suddenly the loglikelihood goes to around -900.
Then it keeps on proceeding, untill finally a error comes that the maximum iteration has been obtained. Now the final model has loglikelihood of around -900.
But initially till 3500 iteration, it had a loglikelihood of -200. So finally should i take loglikelihood as -200 or -900?
Praveen Kumar Mhttps://la.mathworks.com/matlabcentral/profile/authors/8711788-praveen-kumar-mtag:la.mathworks.com,2005:Question/4673232019-06-16T13:53:37Z2019-06-17T10:48:45Zhow can i store the solution (3D mtarix) and its value for a population of Ni have a population of N elements and each produce a certain solution configuration 3D matrix( for example solution X is X(:,:,1)=[1 2 3;4 5 6] and X(:,:,2)=[7 2 3;9 5 8]) this configuration results in an objective function or penalty function equals to 90) i need to store all the solution configurations for all the N population and the corresponding penalty function so that i'll report the best solution reached and its value&configuration. i need it to be fast. thank youDalia Rashedhttps://la.mathworks.com/matlabcentral/profile/authors/11211758-dalia-rashedtag:la.mathworks.com,2005:Question/4674402019-06-17T10:46:31Z2019-06-17T10:46:31ZPCA on an imageHi there,
I'm trying to apply PCA on an single image and i'am using the same porgram that i used to apply PCA to a grupo of images that are part of the data basis of a neuronal network that i am creating. The thing is that i need to apply PCA to a single image to be that image the input to the neuronal network that i created but it doesnt work.
Anyone has any idea of how can I apply PCA to an image of 50x50 saved as vector of 2500 to have an image of 90?
Thanks a lot.Laura Bachiler Matallanahttps://la.mathworks.com/matlabcentral/profile/authors/6302277-laura-bachiler-matallanatag:la.mathworks.com,2005:Question/4674352019-06-17T10:26:41Z2019-06-17T10:43:39ZSlope of experimental dataHello, everyone. I need a help. Thank you in advance. How can I determine the slope of experimental data.
I have this data:
x = [ log(0.12) log(0.09) log(0.06) log(0.03) log(0.015)];
y1 = [ log(313700) log(112100) log(62840) log(4811) log(511.2)];
Thanks for help!
Best regardsRadost Ivanovahttps://la.mathworks.com/matlabcentral/profile/authors/15674796-radost-ivanovatag:la.mathworks.com,2005:Question/4674382019-06-17T10:41:26Z2019-06-17T10:42:30Zdoes anyone simulate the ac3_field oriented control drive for 5hpplease help me out to simulate the drive for 5hp induction motor
i am unable to retune the parameters as given by thius example. the results are unsatisfactory
https://in.mathworks.com/help/physmod/sps/powersys/ug/advanced-users-retune-the-drive-parameters.html
is anyone have the correct detailed model or procedure
manish kumarhttps://la.mathworks.com/matlabcentral/profile/authors/11716896-manish-kumartag:la.mathworks.com,2005:Question/2610752015-12-20T10:04:59Z2019-06-17T10:41:52ZHow can I run matlab connected to arduino more than once?
I have a problem with connecting my arduino uno to matlab.. It actually runs perfectly for the first time but when I run it again it says this (Failed to open serial port COM4 to communicate with Arduino board Uno. Make sure there is no other MATLAB arduino object for this board. For troubleshooting, see Arduino Hardware Troubleshooting.
.. I'm using this command to connect: a = arduino('com4','uno') ..
If anyone can help here I would appreciate it ...hamzah alamoodihttps://la.mathworks.com/matlabcentral/profile/authors/7312740-hamzah-alamooditag:la.mathworks.com,2005:Question/4674082019-06-17T07:22:03Z2019-06-17T10:41:33ZCan anyone help to fix the line 55 of my code ?Dear,
I would like to get help by fixing the line 55 of my code
it gives more errors
exmple : gvd_curve_pcf2=1
and
[pl_fib_dom, pl_fib_loss]=gvd_curve_pcf2;
so it says that gvd_curve_pcf2 is not found
Please HelpFabrice shaohttps://la.mathworks.com/matlabcentral/profile/authors/9817607-fabrice-shaotag:la.mathworks.com,2005:Question/4674362019-06-17T10:33:57Z2019-06-17T10:33:57ZHow to get the visdiff output ?Hello,
After using a visdiff(file1,file2,'txt') expression, it opens a window with the differencies between the two files, which is exactly what I'm looking for.
But how do you use it as an output ?
At the end, there is :
Number of matching lines: XXX
Number of unmatched lines in left file: XXX
Number of unmatched lines in right file: XXX
How do I get each of them (not the number but the output)
CheersMahahttps://la.mathworks.com/matlabcentral/profile/authors/12015661-mahatag:la.mathworks.com,2005:Question/4674272019-06-17T09:31:46Z2019-06-17T10:31:58ZPARFOR Transparency violation error Why am I getting the transperancy error for the following code?
Error using syms (line 216)
Transparency violation error.
See Parallel Computing Toolbox documentation about Transparency
clc
clear
alpha =4; % Path loss exponent
del = 2/alpha;
R =1;
N = 4;
p_k = [0.15 0.05 0.45 0.35];
epsi = 1;
N_set = 1:N;
lambda_dash = 0.05:0.05:0.5;
spec_eff1 = zeros(length(lambda_dash),N);
parfor vv = 1:length(lambda_dash)
vv
comm_term = lambda_dash(vv)*pi*(epsi+R^alpha).*gamma(1+del)*gamma(1-del);
syms tt
fun_int1 = zeros(1,N);
for k = 1:N
term = 0;
for ii = 1:N
m =max(ii-N+k,0):1:min(k,ii);
p_intf = (factorial(k)./(factorial(m).*factorial(k-m))).*(factorial(N-k)./(factorial(ii-m).*factorial(N-k-ii+m)))./(factorial(N)./(factorial(ii).*factorial(N-ii)));
term =term + (sum(p_k(ii).*p_intf.*((2^(tt)-1).*m./k).*((epsi+R^alpha).*(2^(tt)-1).*(m./k) + epsi).^(del-1)));
end
f = exp(-comm_term.*term);
fun_int1(k) = vpa(int(f,[0 inf]));
end
spec_eff1(vv,:) = fun_int1;
end
spec_eff = sum(p_k.*spec_eff1,2);
semilogy(lambda_dash,spec_eff,'k-')
hold on
grid onIIT Panhttps://la.mathworks.com/matlabcentral/profile/authors/15667399-iit-pantag:la.mathworks.com,2005:Question/4674292019-06-17T09:48:56Z2019-06-17T10:28:04Zhow to display coefficient and offset on graph?I'd like to display some values to plot. What should I do ?
A=xlsread('A.xlsx');
t=A(:,1);
i=A(:,2)/10^(2);
ft = fittype('a*exp(-x/b)+c');
F=fit(t,i,ft)
b = 1/F.b;
offset = F.c;
plot(t,i);
hold on;
plot(F)
hold off
It's an example plot, I'd like to make a plot through codes like this figure.
Jaehwi Bonghttps://la.mathworks.com/matlabcentral/profile/authors/15010159-jaehwi-bongtag:la.mathworks.com,2005:Question/4674342019-06-17T10:22:15Z2019-06-17T10:22:15Zmatlab function not recognised by excelHello,
I have generated a matlab function and then taken the second derivitive. I want to place this function within an excel spreadsheet column where I change 'x' for 'c' which is the excel column.
I am doing this to create a iterative function.
the function is
- (154886787*sin((381*x)/200 + 319/200))/400000 - (1139910777*sin((1797*x)/1000 - 783/500))/2500000 - (222034827*sin((1229*x)/1000 + 1537/1000))/3125000
the excel error is 'The formula contains unrecognized text.' whilst excel recognises sin can anyone help please?
gsGavin Seddonhttps://la.mathworks.com/matlabcentral/profile/authors/6295967-gavin-seddontag:la.mathworks.com,2005:Question/4674322019-06-17T10:13:26Z2019-06-17T10:20:29ZNeural network of a single layerHow do I form a neural network with a single layer, so that it wont contain any hidden layer.Monsij Biswalhttps://la.mathworks.com/matlabcentral/profile/authors/8298631-monsij-biswaltag:la.mathworks.com,2005:Question/4674332019-06-17T10:13:55Z2019-06-17T10:13:55ZHow can i limit the assets selected in a portfolio optimisationHello,
I am working on a portfolio optimization using the function fmincon. In particular I have the following problem:
%value of lambda (coefficient of risk aversion)
lambda=[0.01];
%initial weights guess (i have a vector of initial assets weights)
x0=Weights';
%equality constraint Aeq * x = beq such that the sum of weights must be 1
Aeq=[repmat(ones,1,size(Weights,1))];
beq=[1];
%lower and upper bound (lower bound 0 and upper bound 1)
lb=repmat(zeros,size(Weights,1),1);
ub=repmat(ones,size(Weights,1),1);
%set the objective function (maximize the investor utility function as: Weights*Returns - Lambda*Weights'*VarianceCovariance*Weights)
fun= @(x) -((x*Returns)-(lambda*x*(VarianceCovariance)*x'));
%optimize
result=fmincon(fun,x0,A,b,Aeq,beq,lb,ub);
So far I have only one constraint, namely that the sum of weights must be equal to one. Hower i would like to add another one, in particular i want to limit the number selected to a specific number. My universe is composed by 2000 stocks, but i want only 100 of them. As you can see the universe is too large in order to apply an eventually combination formula (even because my intention is to put this optimization in a loop because i want to solving this for a different level of lambda).
Could someone help me?
Armando Martinohttps://la.mathworks.com/matlabcentral/profile/authors/9793265-armando-martinotag:la.mathworks.com,2005:Question/4674312019-06-17T10:11:48Z2019-06-17T10:11:48ZAbout the Matlab Example JPEG Image Deblocking Using Deep LearningHi,
In the matlab example of "JPEG Image Deblocking Using Deep Learning", the network is trained based on the Luminance of Color Image. If there is a Gray scale image, is it possible to use this network? if yes, can you provide suggestions to detect the residual image?
Thanks
pallab choudhuryhttps://la.mathworks.com/matlabcentral/profile/authors/12249732-pallab-choudhurytag:la.mathworks.com,2005:Question/4562922019-04-14T16:42:56Z2019-06-17T10:04:00ZHow limit the number of stocks in a portfolio optimisation?How can i set a cardinality constraint that limit the number of assets in fmincon?
I am trying to optimize an investor's utility function using fmincon, namely:
max W*R-lambda(W*VAr*W)
subject to:
sum(W)==1
sum(N)<=80
where W is the vector of weights, lambda is the coefficient of risk aversion, Var is the variance-covariance matrix and N is the number of securities.
Using fmincon i have already set the first constraint, but i don't know how to set the second one, namely selecting only a certain numbers of securities from my universe (in other words i would like to replicate the maxnum assets that i can find the the portfolio object).Armando Martinohttps://la.mathworks.com/matlabcentral/profile/authors/9793265-armando-martinotag:la.mathworks.com,2005:Question/3747662017-12-28T10:54:13Z2019-06-17T09:50:19ZDetermining Average Heart Rate of ECG Signal <</matlabcentral/answers/uploaded_files/99726/soruu.png>>
I have this ECG Signal. I am trying to determine the average heart rate. I do not know how to determine it . Maybe using flowing graph by refreshing it on every ms by this, signal may shift through right . Every method will be useful for me . The main issue is determining average heart rate .
Trevor Badjihttps://la.mathworks.com/matlabcentral/profile/authors/9043173-trevor-badjitag:la.mathworks.com,2005:Question/4674172019-06-17T08:23:09Z2019-06-17T09:44:52Zmatlab file on disk might be emptyWell, I frequently get this error now, which makes it nearly impossible to improve my codes, because I always have to save the file under a new name. Is anyone familiar with this problem (aktuelles Windows 10, aktuelles Matlab R 2018.b)? I'm grateful for any hints that might solve this issue....
Thanks a lot!
PeterPeter Bäuerlehttps://la.mathworks.com/matlabcentral/profile/authors/4802817-peter-bauerletag:la.mathworks.com,2005:Question/4674282019-06-17T09:44:45Z2019-06-17T09:44:45ZI have IgorTime data in which time:units = "seconds since 1904-01-01". I would like to convert this seconds to datevc.I have attached the file (IgorTime).
Thank youVishnu Dhakadhttps://la.mathworks.com/matlabcentral/profile/authors/11106145-vishnu-dhakadtag:la.mathworks.com,2005:Question/4674042019-06-17T06:53:48Z2019-06-17T09:36:40ZGenerating vectors of length N with only -1s and 1s.I want to generate some M number of vectors of length N with the entries restricted to -1s and 1s and the vectors should not be repetitive. Is it possible to do so? If yes, how?Aditya Petetyhttps://la.mathworks.com/matlabcentral/profile/authors/12043372-aditya-petetytag:la.mathworks.com,2005:Question/4674242019-06-17T09:22:40Z2019-06-17T09:33:16ZComputing a double Integral using a two riemann sums of a f(x,y,z) and graphing multiple isosurfaces of the resulting double integralAdmittedly, I haven't made much progress on trying to acomplish what I mentioned in the tite. I've tried everything from for loops to sum commands and more and I just can't even get the right expression for the double integral (because I can calculate that it doesn't match analytical solutions for the double integral).
Basically, I'm trying to compute the potential and field of a uniform spherical shell of charge and plot the results in the space outside the shell. From my research, it seemed to best way to plot this would be to over plot isosurface plots for different isovalues on the same figure to show how the potential and electric field change with distance from the sphere. But that is my second problem. I can't even compute the double inegral properly. So, my question is twofold,
1) how can I compute a double integral using riemann sums that contain symbolic variables acting as constants?
2) how can I plot the resulting expression in 3 dimensions considering I would have a function of three variables?
The current state of my code to calculate the potential (which I define first and then later will take the gradient to get the electric field) is as follows:
syms r phi theta % symbolic values representing a random point in space outside a uniformly charged spherical shell
% constants
N = 3; % total number of increments to divide the riemann sum into
Q = +20 .* 1e-9; % total charge on sphere
R = 1; % radius of sphere is 1 meter
sigma = Q/(4*pi*(R^2)); % uniform surface charge denisty
eps0 = 8.854e-12;
kC = 1/(4*pi*eps0); % coulomb's constant
dphi = 2*pi/N; % discretizing the interval over which I sum
dtheta = pi/N;
% Performing two riemann sums
% dA = R^2.*cos(thetaprime).*dphi.*dtheta; small area on surface of sphere
% in spherical coordinates
phiprime = linspace(0,2*pi,N);
thetaprime = linspace(0,pi,N);
dInt1 = sym(zeros(0,N)); % preallocating space allowing the presence of symbols
dInt2 = sym(zeros(0,N));
for e = 1: length(phiprime)
for m = 1: length(thetaprime)
dInt1(m) = dInt1 + ((R^2).*cos(thetaprime).*dphi.*dtheta)./sqrt((r.*sin(theta).*cos(phi) - R.*sin(thetaprime).*cos(phiprime)).^2 + (r.*sin(theta).*sin(phi) - R.*sin(thetaprime).*sin(phiprime)).^2 + (r.*cos(theta) - R.*cos(phiprime)).^2)
end
dInt2(e) = dInt2 + sum(dInt1);
end
Int = sum(Int2);
Vtot = kC*sigma.*Int; % total symbolic expression for electric potential
%% Computing Values for Vtot at various points in space and plotting them
rinterval = linspace(1,4,12);
phiinterval = linspace (0,2*pi,12);
thetainterval = linspace(0,pi,12);
[X,Y,Z] = meshgrid(rinterval,phiinterval,thetainterval);
Vcont = subs(Vtot, [r,phi,theta], {X,Y,Z}); % substituting 2D coordinates now for symbolic values
Right now I am currently getting the error:
Error using symengine
Array sizes must match.
Error in sym/privBinaryOp (line 1022)
Csym = mupadmex(op,args{1}.s, args{2}.s, varargin{:});
Error in + (line 7)
X = privBinaryOp(A, B, 'symobj::zipWithImplicitExpansion', '_plus');
Error in Numerical_Integration_of_2D_Surfaces (line 27)
dInt1(m) = dInt1 +
((R^2).*cos(thetaprime).*dphi.*dtheta)./sqrt((r.*sin(theta).*cos(phi) -
R.*sin(thetaprime).*cos(phiprime)).^2 + (r.*sin(theta).*sin(phi) -
R.*sin(thetaprime).*sin(phiprime)).^2 + (r.*cos(theta) - R.*cos(phiprime)).^2)
Thanks in advance!Andrewhttps://la.mathworks.com/matlabcentral/profile/authors/15032018-andrewtag:la.mathworks.com,2005:Question/4672912019-06-16T05:23:57Z2019-06-17T09:32:31ZInterpolation of a scatter plot Hello ;I would be most grateful if someone could give me a helping hand. i have a scatter plot where the the third variable is velocity color coded for each pair of (x,y)I woud like to interpolate this plot to have more points.below is a figure of what i have and my code as well . thanks in advance.
the interpolated points are the red piont of the second figure is having just 9 pionts. i would like to apply that to the first figure which is what i have .
plotTypes = {'mean_velocity','std_velocity','mean_pd', 'std_pd'};
for i = 1: length(plotTypes)
figure
plotType = plotTypes{i};
%subplot(1,length(plotTypes), i);
hold all ;
legendLabels = cell(1,length(plotData));
for j = 1:length(plotData)
xPlot= plotData{j}.data(:, idx.x);
yPlot= plotData{j}.data(:, idx.(plotTypes{i}));
plot(xPlot,yPlot, '-o','color',k(j,:));
legendLabels{j} = ['Y = ', num2str(plotData{j}.y)];
end
legend(legendLabels);
title(plotTypes{i}, 'Interpreter', 'none');
xlabel('x position')
ylabel(plotTypes{i}, 'Interpreter', 'none')
end
%% Generating the 3D color plot
% figure
for i = 1: length(plotTypes)
figure
legendLabels = cell(1,length(plotData));
% subplot(1,length(plotTypes), i);
hold all
for N=1:size(plotData,2)
pz =150;
plotData{1,N}.data();
x=plotData{1,N}.data(:,1);
y= plotData{1,N}.data(:,2);
%if i ==3
% z= plotData{1,N}.data(:,(i+2));
%end% Z(:,N) =plotData{1,N}.data(:,(i+2));
scatter(x,y,pz,plotData{1,N}.data(:,(i+2)),'filled')
legendLabels{N} = ['Y = ', num2str(plotData{N}.y)];
end
%%Interpolation into a gridded data
%F =scatteredInterpolant(x,y,Z);
%[xq,yq]=meshgrid(linspace(20,230,100));
%cq =F(xq,yq);
%h=pcolor(xq,yq,cq)
%legendLabels{N} = ['Y = ', num2str(plotData{N}.y)];
legend(legendLabels);
title(['3D plot of position against ',plotTypes{i}], 'Interpreter', 'none')
xlabel('X(mm)')
ylabel('Y(mm)')
H = colorbar;
ylabel(H, plotTypes{i});
end
Yannick Tabot Njamihttps://la.mathworks.com/matlabcentral/profile/authors/9913485-yannick-tabot-njamitag:la.mathworks.com,2005:Question/4386642019-01-07T19:12:11Z2019-06-17T09:27:47ZStrange behavior of the editor in the forumThe editor in the forum is still driving me crazy. With the old version I could at least type my messages in an external editor, but now the text field is too smart to allow this.
When I type some code (Ctrl-E to enter the code style, then "for i = 1:10"), the editor is such smart, that it adds an "end" automatically. But I do not want such an "end", because my example is clear already without it. After this line, I press Enter and Ctrl-E again to leave the code style. Now I have to spend some time to get rid of the "end".
Sometimes the text field seems to loose the focus partially. I've tested this in Firefox only: While the typed characters appear in the text field, Firefox interpretes the keystrokes also and scrolls through the page exhaustively, such that I cannot see, what I type anymore. I type some characters blindly and scroll back to check, if it is correct. With the next keystroke the page is scrolled again. This is extremely annoying.
When I leave the code style, there are a certain number of spaces infront of the cursor. Trying to delete them let me exceed the first character frequently, such that I delete the code style before. Therefore I need to use "Pos 1" at first, then "Shift+End" to mark all spaces, "Delete" to remove them and then I can start typing from the first character.
It is hard to insert a link, but even worse to insert a string without formatting. Because I appreciate the correct spelling of names of persons, I copy&paste the names from the display by copy&paste. Unfortunately the editor is such smart, that it inserts a link automatically and I need a bunch of keystrokes to make it a standard text. I should append a move of this, because during the editing some parts of the string disappear intermediately and reappear magically, when a space is added.
This feels very weird. I have not seen such a crazy and unintuitive editor before. Typing answers in the forum increases my stress level, because the interface does not treat keyboard inputs like any other software.
What a pity, that the field for typing is not recognized as text field anymore, such that the auto-spell-correction of the browser does not work. I apologize for all of my typos.
There are many forums with working editors for text, links, code and citations. Markdown, BBCode etc. are established methods. Matlab Answers has problems with the interface for many years now. It is time to fix and simplify this until it works, instead of making it smarter and cooler.
Has this topic been diskussed in (sorry, I'm typing blind again, because of the mentioned effects of scrolling away... darn) forum already? Do others suffer from the same problems? Is the editor more intuitive in other browsers than Firefox? Does somebody use an external editor like XEmacs + macros successfully to create answers with copy&paste including links and images?Janhttps://la.mathworks.com/matlabcentral/profile/authors/869888-jantag:la.mathworks.com,2005:Question/4674262019-06-17T09:27:11Z2019-06-17T09:27:11ZHow to set bounds for coefficents when fitting Exponential?I'd like to give boundary for coefficient(a, b and c). Whenever I run my fitting, it should give the coefficients within boundary. For instance, I want to get only b value of over 200 below 400.
I'm trying to make it with 'fitoptions', but it doesn't work in a code.
How should I do for that?
I attached my data file for example.
A=xlsread('A.xlsx');
t=A(:,1);
i=A(:,2)/10^(2);
ft = fittype('a*exp(-x/b)+c');
%options = fitoptions('ft', 'lower',[100000 400 10000], 'upper',[0 200 0]);
F=fit(t,i,ft) %, options)
General model:
F(x) = a*exp(-x/b)+c
Coefficients (with 95% confidence bounds):
a = 5.558e+04 (5.525e+04, 5.591e+04)
b = 373.5 (366.4, 380.7)
c = 5.171e+04 (5.135e+04, 5.207e+04)Jaehwi Bonghttps://la.mathworks.com/matlabcentral/profile/authors/15010159-jaehwi-bongtag:la.mathworks.com,2005:Question/4674192019-06-17T08:38:02Z2019-06-17T09:26:07ZHow to get different colours for different regions for this problem How to get different colours for different regions for this problem? Here are 10 regions and I want to colour the regions? How to modify the code to get the desired result?
x=0:.00001:1;
y=x.*x;
plot(x,y,'r')
hold on
z=sqrt(x);
plot(x,z);
hold on
y=x;
plot(x,y,'g')
y=1-x;
hold on
plot(x,y,'k')
x=0:.00001:.334;
y=1-2*x;
hold on
plot(x,y,'r')
axis([0 1 0 1])
pallav palhttps://la.mathworks.com/matlabcentral/profile/authors/2325134-pallav-paltag:la.mathworks.com,2005:Question/4669302019-06-13T14:16:50Z2019-06-17T09:22:06ZHow to compare two matrices of different dimentions and get the result in new columnHi everyone,
i wanne compare data in two column and get the result in a new column if my condition is true.
A = [2000;1950 ; 1980;2500 ; 2000 ; 5000 ; 2300 ;2000'];
B = [2;2;1;3;1;5;3;3 ; 2;3];
wanne go through all value in B and write in new column when they meet/ equal to 2000.
many thanks
/SAShayanAhttps://la.mathworks.com/matlabcentral/profile/authors/11358641-shayanatag:la.mathworks.com,2005:Question/4674212019-06-17T08:51:59Z2019-06-17T09:20:39ZDot indexing error when adding chapter to report, no further help givenHi all,
I am using the Report Generator toolbox and trying to add a chapter to the report object, but I get an error that I have no idea how to fix.
Here is a simplified version my code:
rpt = mlreportgen.report.Report(reportPath,formatStr);
ch = Chapter;
ch.Title = 'txt';
sec1 = Section('txt');
txt1 = 'txt';
add(sec1,txt1);
figures = thisFunctionMakesPlots(plotRelatedInputs);
figCaptions = {'cap','tion'};
for idxFig = 1:numel(figures)
fig = Figure(figures(idxFig));
fig.Snapshot.Caption = figCaptions{idxFig};
fig.Snapshot.Height = '5in';
add(sec1,fig);
end
add(ch,sec1);
sec2 = Section('txt');
txt2 = 'txt';
add(sec2,txt2);
[figures, figCaptions] = anotherFunctionThatMakesPlots(plotRelatedInputs);
for idxFig = 1:numel(figures)
fig = Figure(figures(idxFig));
fig.Snapshot.Caption = ['Text appended to ' figCaptions{idxFig}];
fig.Snapshot.Height = '5in';
add(sec2,fig);
end
add(ch,sec2);
add(rpt,ch);
The error message below is given after trying to run the last line.
Dot indexing is not supported for variables of this type.
Error in mlreportgen.report.Figure/createSnapshotFigure
Error in mlreportgen.report.Figure/getSnapshotImageImpl
Error in mlreportgen.report.Figure/getContent
Error in mlreportgen.report.ReportForm/fillHole
Error in mlreportgen.report.ReporterBase/processHole
Error in mlreportgen.report.ReportForm/fillForm
Error in mlreportgen.report.ReporterBase/getDocumentPart
Error in mlreportgen.report.ReporterBase/getImpl
Error in mlreportgen.report.internal.LockedForm.add
Error in mlreportgen.report.internal.LockedForm.add
Error in mlreportgen.report.ReportForm/fillHole
Error in mlreportgen.report.Section/processHole
Error in mlreportgen.report.ReportForm/fillForm
Error in mlreportgen.report.ReporterBase/getDocumentPart
Error in mlreportgen.report.ReporterBase/getImpl
Error in mlreportgen.report.Section/getImpl
Error in mlreportgen.report.internal.LockedForm.add
Error in mlreportgen.report.internal.LockedForm.add
Error in mlreportgen.report.ReportForm/fillHole
Error in mlreportgen.report.Section/processHole
Error in mlreportgen.report.Chapter/processHole
Error in mlreportgen.report.ReportForm/fillForm
Error in mlreportgen.report.ReporterBase/getDocumentPart
Error in mlreportgen.report.ReporterBase/getImpl
Error in mlreportgen.report.Section/getImpl
Error in mlreportgen.report.internal.LockedForm.add
Error in mlreportgen.report.ReportBase/add
It is quite useless, as I am not able to click into any of the levels to try and understand the problem better, so I have no idea how to fix this. Please help! Thanks in advance.K Whttps://la.mathworks.com/matlabcentral/profile/authors/12068449-k-wtag:la.mathworks.com,2005:Question/4668292019-06-13T02:11:22Z2019-06-17T09:15:19Zhow to combine the coordinates of points of 2 column vectors for specific widthThanks for community support. let me phrase my questions with more detail lets suppose i have vertices of a tea cup.
Vx =[ 0;1;2;0;9]
Vy = [1;1;,2;;3]
Vz= = [38,32,-1]
They are cancatenated in a larger matrix = [Vx Vy Vz].
After sorting, i want to find first elements or coordinates like (0,1,38) here in Vx,Vy,Vz wherever they meet or match, it should be labelled as 5 in that particular grid.
Your guidance will be highly appreciated.
regardsMohammad Shafiq Khanhttps://la.mathworks.com/matlabcentral/profile/authors/13647580-mohammad-shafiq-khantag:la.mathworks.com,2005:Question/4673612019-06-16T22:15:11Z2019-06-17T09:10:42Zhow to extract data from the fixed-width-field format using fscanf or textscanI am trying to parase large file, containing among others numerical data fixed in fixed-width-fields format without whitespaces (or any other separators) between the fields. Consider the example:
1223244
55 6 788
1122 3 4
In this text each line contains four numbers each - two digits wide. Expected result after parsing this flie is:
1 22 33 44
55 6 7 88
11 22 3 4
The prerformance is important for me, as the files I read may be hunreds of MBs large. From my experiments I discovered, that fgetl() is drammatically slower, than fscanf (I did not check the performance, but I expect, that textscan should also be significantly faster.
The problem is that I cannot find the way to parse data like this with fscanf or textscan. Could someone tell, if it is possible at all? If not, is there any other way to parse such a text file with good performance?
P.S. format of actual string is, of course, somewhat more complicated. Example string is:
1101332.18685714711829.064533733772535.874264373485 0 0
this string should be parsed into the numbers with the following widths: 8, 16, 16, 16, 8, 8, which in this particular case would result in the following numbers:
110
1332.18685714711
829.064533733772
535.874264373485
0
0
P.S.2: Differnence between the performance of fgetl and fscanf: On my laptop for the file, which contains 35597 lines the following code with fscanf complete in 0.253614 seconds
function [data] = test_fscanf_nodes_only_01()
file_name = 'myfile.txt';
file_id = fopen (file_name, 'rt');
cleanup_obj = onCleanup(@() fclose(file_id));
data = fscanf(file_id, '%8d%16f%16f%16f%8f%8f', [6, Inf]);
end
while the following code with fgetl needs 6.343209 seconds to complete, even though it does much less
function [data] = test_fscanf_nodes_only_02()
file_name = 'myfile.txt';
file_id = fopen (file_name, 'rt');
cleanup_obj = onCleanup(@() fclose(file_id));
lines_count = 0;
while ~feof(file_id)
current_line = fgetl(file_id);
lines_count = lines_count + 1;
end
data = 1;
fprintf('Lines count: %d', lines_count);
end
The main problem with the first snippet is that it returns wrong result (because for fscanf the width of the field counts from the first digit it finds and not from the current position of the file pointer (which means, that the leading whitespaces are not counted as field width).
EDIT: The dimension in fscanf is changed from [5, Inf] to [6, Inf] according to Jan's comment.Dmitrii Semikinhttps://la.mathworks.com/matlabcentral/profile/authors/15367413-dmitrii-semikintag:la.mathworks.com,2005:Question/449172012-07-31T06:56:29Z2019-06-17T09:09:32ZHow is the MarkerSize of a 'Circle' marker definedHi,
I'm ploting a 'Circle' marker using the 'plot' command.
I'm setting the marker size using 'MarkerSize' property.
e.g.:
plot(x,y,'or','MarkerSize',10);
Figure 'Units' are 'pixels'.
My question is what does the number 10 means (in pixles)?
I played with it and it is not the radius or diameter in pixels.
Any suggestions?
Thanks, MoranMoran Shochathttps://la.mathworks.com/matlabcentral/profile/authors/2913387-moran-shochattag:la.mathworks.com,2005:Question/4672222019-06-15T10:51:14Z2019-06-17T09:09:04Zranova with two within factorsHello everyone,
I have a question about how to do a repeated measures anova in Matlab. I have data from 20 people who were tested in 4 conditions each: treatment A pre test, treatment A post test, treatment B pre test, treatment B post test. I want to use time and treatment as factors. However I only managed an anova with one factor. Here's what I got so far:
datatable = cell2table(struct2cell([pre.A, pre.B, post.A, post.B]'));
datatable.Properties.VariableNames = {'pre_A','pre_B','post_A','post_B'};
rm = fitrm(datatable, 'pre_A,pre_B,post_A,post_B~1','WithinDesign',[1:4]);
ranovatable = ranova(rm)
How do I introduce the treatment as a second within factor? I read the documentation but did not find anything I could make use of. Thank you so much in advance!Rose Potterhttps://la.mathworks.com/matlabcentral/profile/authors/15159153-rose-pottertag:la.mathworks.com,2005:Question/4485342019-03-06T10:41:26Z2019-06-17T09:06:33Zwhile installing raspberry pi hardware support package having an error in write firmware step. while installing raspberry pi hardware support package for raspberry pi 3 model B through MATLAB 2018a having an error at writer firmware step.
error writing firmware to the memory card: Firmware write has timed out, try again.
kindly, help me out to resolve this problem.
I have run MATLAB as administrator. also formatted the card as sd card formatter.
ARCHANA DUBEYhttps://la.mathworks.com/matlabcentral/profile/authors/14902846-archana-dubeytag:la.mathworks.com,2005:Question/4674062019-06-17T07:06:57Z2019-06-17T09:05:22ZHow to find position of arrayFor example i have data like this [11111100001111]
Now i need to find out the position of first 1 and last 1 of first group of 1s and then position of first 1 and last 1 of second group of 1s. How do i do this??
i have used' find' to find the position of all 1s but i dont want all...instead 1 want only the first and last position of groupof 1sWind flowerhttps://la.mathworks.com/matlabcentral/profile/authors/15676526-wind-flowertag:la.mathworks.com,2005:Question/4673282019-06-16T15:39:27Z2019-06-17T09:02:25ZQuadprog 'interior-point-convex' failureDear Matlab Gurus,
I have a problem with Matlab quadprog function.
A few years ago I implemented a code using quadprog with the 'active-set' algorithm, and it worked pretty well. The problem is characterised by a structurally dense hessian and inequality constraint matrix (see data attached).
Now this algorithm is no more available and only 'interior-point-convex' and 'trust-region-reflective' can be used. However, the 'trust-region-reflective' cannot be used with inequality constraints. So the choice is reduced to 'interior-point-convex' that is not able to solve the problem:
clear variables, close all
% load problem
load('testData.mat');
% quadprog setup (R2018b)
opts = optimoptions(@quadprog,...
'Algorithm','interior-point-convex');
tic
[x,fval,exitflag,output,lambda] = quadprog(H,f,A,b,Aeq,beq,[],[],x0,opts);
toc
The output is
The interior-point-convex algorithm does not accept an initial point.
Ignoring X0.
No feasible solution found.
quadprog stopped because it was unable to find a point that satisfies
the constraints within the default value of the constraint tolerance.
<stopping criteria details>
The funny is that I already have a feasible solution x0, but the 'interior-point-convex' algorithm does not accept an initial point:
% feasibility check
any(A*x0-b > 0)
ans =
0
When using the 'active-set' algorithm with a Matlab version < 2016 everything is fine and the algorithm ends correctly.
clear variables, close all
% load problem
load('testData.mat');
% quadprog setup (R2015b)
opts = optimoptions(@quadprog,...
'Algorithm','active-set');
tic
[x,fval,exitflag,output,lambda] = quadprog(H,f,A,b,Aeq,beq,[],[],x0,opts);
toc
with output
Warning: The 'active-set' algorithm will be removed in a future release. To avoid this warning or a future error, choose a
different algorithm: 'interior-point-convex' or 'trust-region-reflective'.
> In quadprog (line 427)
In test_quadprog_solvers (line 10)
Optimization terminated.
Elapsed time is 2.239872 seconds.
I have seen that fmincon still have the 'active-set' algorithm and I am wondering if with a proper setup of options I can trick the optimizer to solve a purely quadratic programming. I tried:
clear variables, close all
% load problem
load('testData.mat');
% fmincon setup (R2018b)
opts = optimoptions(@fmincon,...
'Algorithm','active-set',...
'SpecifyObjectiveGradient',true);
tic
[xred,fval,exitflag,output,lambda] = fmincon(@(x)quadFcn(x,H,f),x0,A,b,Aeq,beq,[],[],[],opts);
toc
With
function [fval,gval] = quadFcn(x,H,f)
fval = .5*x'*H*x+f'*x;
if nargout > 1 % gradient required
gval = H*x+f;
end
end
And the result is fine
Local minimum possible. Constraints satisfied.
fmincon stopped because the predicted change in the objective function
is less than the default value of the function tolerance and constraints
are satisfied to within the default value of the constraint tolerance.
<stopping criteria details>
Elapsed time is 3.966116 seconds.
But the calculation time is almost doubled with respect to the quadprog function with 'active-set' algorithm, and things are worse for more complex problems than this simple benchmark.
Any idea to restore the original behavior or performance?
Thank you in advanceFabio Freschihttps://la.mathworks.com/matlabcentral/profile/authors/1568935-fabio-freschitag:la.mathworks.com,2005:Question/4670682019-06-14T10:09:27Z2019-06-17T08:59:22ZHow can I compute spectrogram for data vector containing NaN values?Dear community,
I am currently working on seismic recordings and I need to compute the spectrogram. The dataset has been cleaned in advance, and thus the original vector contains small portions of NaN values (about a few seconds each with a sample rate of 100 Hz).
However, spectrogram function cannot be applied to NaN values without compromising the entire result, and applying it to not NaN values (applied to data(~isnan(data)) would provide incorrect results (spectrogram function assumes that the sample rate is homogeneous which would no longer be the case).
I do not really know how to manage this issue, and to compute a correct power spectral density for my data, if anyone has a clue...
Thank youSuzanne CARON--SAUTEJEAUhttps://la.mathworks.com/matlabcentral/profile/authors/7779582-suzanne-caron-sautejeautag:la.mathworks.com,2005:Question/4674222019-06-17T08:52:50Z2019-06-17T08:52:50ZHow do I run a model in Simulink from my MATLAB function? I got a problem with appending simulink in matlab. The problem is that I have a DC motor and I need to find the parameters of the resistance and the coil using matlab. As you can see in the code, I need the values for the resistance and the coil (named x) and I need to obtain a speed close to vo=700. I don't know how to do this. I tried using the matlab function block and I don't know how to use it. ok, my code have function e=(vo-v)/vo, where v0=700. i put the v= fdcmotor(x), where v=sim('DCmotor'). DCmotor is the name of the program in the simulink.
Ana Mariahttps://la.mathworks.com/matlabcentral/profile/authors/15677071-ana-mariatag:la.mathworks.com,2005:Question/4673392019-06-16T18:15:57Z2019-06-17T08:48:43ZI installed MTALAB 2015 on my PC having 32 bit Windows 7 , activation also completed but when i try to run matlab , i got error "Fail; to start Java virtual machine, JNI Error 3". Plz help meI installed MTALAB 2015 on my PC having 32 bit Windows 7 , activation also completed but when i try to run matlab , i got error "Fail; to start Java virtual machine, JNI Error 3". Plz help meArchana Bhatnagarhttps://la.mathworks.com/matlabcentral/profile/authors/15489532-archana-bhatnagartag:la.mathworks.com,2005:Question/4573192019-04-19T05:42:21Z2019-06-17T08:44:40ZUser login in an app deployed with Web app ServerHi everyone,
Im creating an app with app desinger. I will compile this app to be deployed with Matlab Web App Server, to be shared with colleagues in my institution network. I wonder if it is possible to include a login window to ask users to login before use the app.
Thanks.Roberto M Sanchezhttps://la.mathworks.com/matlabcentral/profile/authors/7910260-roberto-m-sancheztag:la.mathworks.com,2005:Question/4649132019-05-31T09:02:48Z2019-06-17T08:39:57ZHow to read only the first term on the file.Hi, I would know if someone can help me with this. In the file I have, I only need to read te first term of the second column, I mean, the total_x number. Anyone know how can I do that?
ThanksMoises Beldahttps://la.mathworks.com/matlabcentral/profile/authors/15593942-moises-belda