https://es.mathworks.com/matlabcentral/answers/questionsMATLAB Answers — New Questions2020-09-29T18:38:50Ztag:es.mathworks.com,2005:Question/6020952020-09-29T18:31:44Z2020-09-29T18:38:50ZHow can I add curves to the Bode plot?
I am trying to make a comparison between my experimental resutl and theoretical result, how can I move that blue curve to the magnitude plot? Below are the code that I used:
s =tf('s');
R = 11.17*10^3;
C = 0.066*10^-6;
B = 1/(1+s*R*C);
lf = [73.79,368.95,737.9,1475.8,2213.7,2951.6,5903.2];
bode(B,lf);
grid;
hold on
mr = [-0.219907686,-0.406756628,-1.061134586,-3.0980392,-5.31200515,-6.792178032,-11.95477235];
pd = [-2.58876,-13.3245,-25.2108,-43.3152,-54.3132,-61.9272,-74.448];
plot(lf,mr);
hold on
plot(lf,pd);Zifeng Qiuhttps://es.mathworks.com/matlabcentral/profile/authors/13438737tag:es.mathworks.com,2005:Question/6021012020-09-29T18:38:47Z2020-09-29T18:38:47ZProblem with debugging a MATLAb code?Hello everybody,
I don't know what'is the problem with my code that I get the following error message" Index exceeds the number of array elements (0)."
Can someone help me fix this problem. Here is my code:
clc
clear all
%Load experminetal data from DSC.csv file
[d,s,r] = xlsread('DSC.csv');
x = d(:,2);
y = d(:,3);
% fit a 7-term Gaussian function to the experminetal data
f = fit(x,y,'gauss7');
%get coefficients of the fitted function
coeffvals= coeffvalues(f);
%Divide coefficients into a,b,c vectors (f=a1*exp(-((x-b1)/c1)^2) + a2*exp(-((x-b2)/c2)^2)+...)
%number of fitted Gaussians
n=7;
%find a1,a2,a3,..
a=coeffvals(1:3:(3*n-2));
%find b1,b2,b3,..
b=coeffvals(2:3:(3*n-1));
%find c1,c2,c3,..
c=coeffvals(3:3:(3*n));
%%find each fitted Gaussian
f1=a(1)*exp(-((x-b(1))./c(1)).^2);
f2=a(2)*exp(-((x-b(2))./c(2)).^2);
f3=a(3)*exp(-((x-b(3))./c(3)).^2);
f4=a(4)*exp(-((x-b(4))./c(4)).^2);
f5=a(5)*exp(-((x-b(5))./c(5)).^2);
f6=a(6)*exp(-((x-b(6))./c(6)).^2);
f7=a(7)*exp(-((x-b(7))./c(7)).^2);
f=f1+f2+f3+f4+f5+f6+f7;
%plot fitted data against experimental data
plot(x,y,x,f1,x,f3,x,f4,x,f6,x,f7,x,f,'linewidth',2)
legend('Real DSC (2-11 N)','f1','f2','f3','f4','f5','Sum of Gaussians')
xlabel('Temperature (K)')
ylabel('Heat flow (W/g)')
%%
%-------------------------------------------------------------------------------------------------------------
%Load experminetal HIT data
[d,s,r] = xlsread('HIT_webplotdigitizer.csv');
t = d(:,2);
y = d(:,3);
% initial guesses for alpha and beta and their lower and upper bound
B0 =[0.8,0.09,0];
%curve-fitting using non-linear curve fit function
FitnessFunction = @(B) norm(y-HIT_curve_fitting_4_Gaussian(B,t,a,b,c));
numberOfVariables = 3; % Number of decision variables
lb =[0,0,0];% Lower bound
ub=[Inf,Inf,Inf]; % Upper bound
A = []; % No linear inequality constraints
b = []; % No linear inequality constraints
Aeq = []; % No linear equality constraints
beq = []; % No linear equality constraints
HITfun1 = @(B,t) HIT_curve_fitting_4_Gaussian(B,t,a,b,c);
% [B,Rsdnrm,Rsd,ExFlg,OptmInfo,Lmda,Jmat] = lsqcurvefit(HITfun1,B0,t,y,lb,ub);
options = optimoptions(@gamultiobj,'CreationFcn',{@gacreationlinearfeasible},'FunctionTolerance',1e-4,...
'MaxGenerations',300,'MaxStallGenerations',200,'PopulationSize',500,'MutationFcn',{@mutationadaptfeasible},...
'CrossoverFraction',0.8,'CrossoverFcn',{@crossoverintermediate});
[B,Fval,exitFlag,Output] = gamultiobj(FitnessFunction,numberOfVariables,A,b,Aeq,beq,lb,ub,options);
% [B,Rsdnrm,Rsd,ExFlg,OptmInfo,Lmda,Jmat] = lsqcurvefit(odefun1,B0,xx,yy,lb,ub);
% plot both fitted curves and experimental data
% figure;
% plot(t,y,t,HIT_curve_fitting_4_Gaussian(B,t,a,b,c),'LineWidth',2)
% legend({'\sigma_H_I_T (2-11 N)','x_o_u_t (Conv. of Gaussians)'})
% xlabel('Temperature(K)')
% ylabel('Stress(MPa)')
Here is the function which is called in the code:
function total = HIT_curve_fitting_4_Gaussian(B, t,a,b,c)
%seTd temp vector
t0=t(1);
tf=t(end);
N=10000;
dt=(tf-t0)/N;
% t=t0:dt:tf;
%----------------------------------------------------------------------------------------------
%function f1
%Second function of the convolution
f1=a(1)*exp(-((t-b(1))./c(1)).^2);
%Obtain T0
miu=b(1);
sigma=c(1)/sqrt(2);
T0_f1=miu-3*sigma;
%construct the firxt part of the convolution
y1=zeros(length(t),1);
for i=1:length(t)
if t(i)<T0_f1
y1(i)=0;
else
y1(i)=B(1)+B(2)*(t(i)-T0_f1);
end
end
%Convolution of these 2 functions
[val,idx]=min(abs(t-T0_f1));
minVal=t(idx);
z1=conv(y1,f1(idx:end),'full');
con1 = z1(1:length(t))*dt;
%---------------------------------------------------------------------------------------------
%function f2
%Second function of the convolution
f2=a(3)*exp(-((t-b(3))./c(3)).^2);
%Obtain T0
miu=b(3);
sigma=c(3)/sqrt(2);
T0_f2=miu-3*sigma;
%construct the firxt part of the convolution
y2=zeros(length(t),1);
for i=1:length(t)
if t(i)<T0_f2
y2(i)=0;
else
y2(i)=B(1)+B(2)*(t(i)-T0_f2);
end
end
%Convolution of these 2 functions
[val,idx]=min(abs(t-T0_f2));
minVal=t(idx);
z2=conv(y2,f2(idx:end),'full');
con2 = z2(1:length(t))*dt;
%----------------------------------------------------------------------------------------
%function f3
%Second function of the convolution
f3=a(4)*exp(-((t-b(4))./c(4)).^2);
%Obtain T0
miu=b(4);
sigma=c(4)/sqrt(2);
T0_f3=miu-3*sigma;
%construct the firxt part of the convolution
y3=zeros(length(t),1);
for i=1:length(t)
if t(i)<T0_f3
y3(i)=0;
else
y3(i)=B(1)+B(2)*(t(i)-T0_f3);
end
end
%Convolution of these 2 functions
[val,idx]=min(abs(t-T0_f3));
minVal=t(idx);
z3=conv(y3,f3(idx:end),'full');
con3 = z3(1:length(t))*dt;
%----------------------------------------------------------------------------------------
%function f4
%Second function of the convolution
f4=a(6)*exp(-((t-b(6))./c(6)).^2);
%Obtain T0
miu=b(6);
sigma=c(6)/sqrt(2);
T0_f4=miu-3*sigma;
%construct the firxt part of the convolution
y4=zeros(length(t),1);
for i=1:length(t)
if t(i)<T0_f4
y4(i)=0;
else
y4(i)=B(1)+B(2)*(t(i)-T0_f4);
end
end
%Convolution of these 2 functions
[val,idx]=min(abs(t-T0_f4));
minVal=t(idx);
z4=conv(y4,f4(idx:end),'full');
con4 = z4(1:length(t))*dt;
%----------------------------------------------------------------------------------------
%function f5
%Second function of the convolution
f5=a(7)*exp(-((t-b(7))./c(7)).^2);
%Obtain T0
miu=b(7);
sigma=c(7)/sqrt(2);
T0_f5=miu-3*sigma;
%construct the firxt part of the convolution
y5=zeros(length(t),1);
for i=1:length(t)
if t(i)<T0_f5
y5(i)=0;
else
y5(i)=B(1)+B(2)*(t(i)-T0_f5);
end
end
%Convolution of these 2 functions
[val,idx]=min(abs(t-T0_f5));
minVal=t(idx);
z5=conv(y5,f5(idx:end),'full');
con5 = z5(1:length(t))*dt;
%----------------------------------------------------------------------------------------
%Create plots
f=f1+f2+f3+f4+f5;
total=con1+con2+con3+con4+con5+B(3);
end
I have attached the .csv file.
Faezeh Maneshhttps://es.mathworks.com/matlabcentral/profile/authors/15758300tag:es.mathworks.com,2005:Question/6020472020-09-29T16:27:07Z2020-09-29T18:37:44Zmatlab 2020 installation for mei am using matlab 2014.is is fine or latest versions are far ahead.
secondly i want to install matlab 2020 for free. any help plzzali hassanhttps://es.mathworks.com/matlabcentral/profile/authors/17127843tag:es.mathworks.com,2005:Question/6020982020-09-29T18:37:42Z2020-09-29T18:37:42ZHow to extract before and after a character up to a certain limit?Hey everyone, I'm playing around with extractBefore and extractAfter and I was wondering if I could get Matlab to extract everything before and after a character up to a specified character boundary. Like so,
str = 'aazbbkkcbbsszaa'
I want to take something like this example string and extract all the characters before and after "c" up until it reaches the letter "z". SO my outputs might look like,
extractAfter = 'bbss'
extractBefore = 'bbkk'
How can I do this?Brett Baxterhttps://es.mathworks.com/matlabcentral/profile/authors/19214710tag:es.mathworks.com,2005:Question/6019122020-09-29T11:57:33Z2020-09-29T18:28:37ZSymsum every other stepHi everybody,
I'm trying to get a symsum runnin' with a count of every other step.
The Formula itself looks like this:
My current code
a=2:2:10
syms p [1 size_x_r_sampling_meter];
f=k^2*p
f1=symsum(f,k,a)
obvjously doesn't work...
Could you please give me a hint, how to solve this problem?
Very best
Christian Christian S.https://es.mathworks.com/matlabcentral/profile/authors/13123336tag:es.mathworks.com,2005:Question/6016902020-09-29T03:42:10Z2020-09-29T18:25:18Zsolution of 3d nonlinear equationx_p, y_p, z_p=(4, 5, 2)
x_1, y_1, z_1=(8, 9, 5)
x_2, y_2, z_2=(2, 5, 1)
x_3, y_3, z_3=(6, 1, 3)
t_1=5.692820*10^-9
t_2=-2.924173*10^-9
t_3=-12.010097*10^-9
c=3.0*10^8
and my three equations are
eqn1 = sqrt((x(s)-x_p)^2+(y(s)-y_p)^2+(z(s)-z_p)^2)-sqrt((x(s)-x_1)^2+(y(s)-y_1)^2+(z(s)-z_2)^2)-(c*t_1)
eqn2 = sqrt((x(s)-x_p)^2+(y(s)-y_p)^2+(z(s)-z_p)^2)-sqrt((x(s)-x_2)^2+(y(s)-y_2)^2+(z(s)-z_2)^2)-(c*t_1)
eqn3 = sqrt((x(s)-x_p)^2+(y(s)-y_p)^2+(z(s)-z_p)^2)-sqrt((x(s)-x_3)^2+(y(s)-y_3)^2+(z(s)-z_3)^2)-(c*t_1)
where only x(s), y(s), z(s) are unknown are rest all are known
BEST REGARDSali hassanhttps://es.mathworks.com/matlabcentral/profile/authors/17127843tag:es.mathworks.com,2005:Question/6020772020-09-29T17:29:47Z2020-09-29T18:24:32ZArrange words and phrases separated by semi-colon into a single columnI am analyzing some journal articles using their keywords. I extracted the keywords from a publication, and they have been saved in the form as shown in the figure.
Keywords and key-phrases are separated by a semi-colon in each cell. Since my least time interval is one month, I'd like to arrange all the key words and phrases in columns corresponding to each month of the year. For example, all the words and phrases in the image would come under a single column 'JAN 2001'. My ultimate goal is to do a frequency analysis of these keywords, and I want 'galaxies' to be considered separate from 'iras galaxies' or 'elliptic galaxies'. I guess repetition of keywords would be allowed within a month as well, since it just shows the trendiness of that concept. How can I separate strings using the semi-colon and arrange them by month? Thank you!Tejas Rajratna Adsulhttps://es.mathworks.com/matlabcentral/profile/authors/18205581tag:es.mathworks.com,2005:Question/3958162018-03-26T04:00:00Z2020-09-29T18:23:26ZWhy do I get "Array indices must be positive integers or logical values" error when using "angle" function?Why do I get "Array indices must be positive integers or logical values" error when using "angle" function?
>> z = 22+i
>> a = angle(z)
>> z =
22.0000 + 1.0000i
ERROR: Array indices must be positive integers or logical values.
MathWorks Support Teamhttps://es.mathworks.com/matlabcentral/profile/authors/4622813tag:es.mathworks.com,2005:Question/6014052020-09-28T16:32:14Z2020-09-29T18:20:06ZHow to fix this error Index exceeds the number of array elements (1) for a linear advection problem ?the problem statement is a linear advection equation with these following conditions
and use grid spacing of dx=1 and apply time setp dt based on CFL numbers 0.5,0.8,1.0. Compute the solution for 100 time steps. To solve this problem I have to use explicit upwind differencing (FTBS).
here is my attempted code, I'm not sure how to fix this code
%define variable
xmin = 0; %min value of x
xmax = 250; %max value of x
dx=1;
c=250; %velcoity
CFL=0.5;
dt=(CFL*dx)/c;
tmax = 100; % max value of t
t=0; %time
N=100; %number of nodes-1
% discretise the domain
x=xmin:dx:xmax;
%set initial condition
for i=1:xmax
if (0<=x(i))&&(x(i)<=50)
u0=0;
elseif (50<=x(i))&&(x(i)<=110)
u0=100*sin(pi*(x-50)/60);
else (110<=x(i))&&(x(i)<=250);
u0=0;
end
end
% loop through time
nsteps = tmax/dt;
for n=1:nsteps
u=u0;
unp1=u0;
%Boundary conditions
u(:)=0;
%upwind scheme
for i = 2:N+2
unp1(i)=u(i)-CFL*(u(i)-u(i-1));
end
%update t and u
t = t+dt;
u = unp1;
%Plot solution
plot(x,u,'bo-','markerfacecolor','b');
pause(0.01);
end Zahraahttps://es.mathworks.com/matlabcentral/profile/authors/13550497tag:es.mathworks.com,2005:Question/3890242018-03-18T10:26:21Z2020-09-29T18:18:13ZWhy does MATLAB R2018a display erroneous message on Ubuntu 16.04?Why does MATLAB R2018a display the following erroneous message on Ubuntu 16.04?
MATLAB is selecting SOFTWARE OPENGL rendering.
/usr/local/MATLAB/R2018a/bin/glnxa64/MATLAB: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version
`GLIBCXX_3.4.22' not found (required by /usr/local/MATLAB/R2018a/bin/glnxa64/libCppMicroServices.so.3.1.1)
I followed the classic installation instructions and I also installed matlab-support.
Michele Loverrehttps://es.mathworks.com/matlabcentral/profile/authors/10772390tag:es.mathworks.com,2005:Question/6020922020-09-29T18:14:50Z2020-09-29T18:17:49Z how to convert matlab ML model to an API service?I already have a ML model trained in MATLAB and i want to convert this model into an API so that I can use this ML model in other apllications
built in some other technology stacks(Java,C# etc) to make predictions.
How do I do this?shreya srivastavhttps://es.mathworks.com/matlabcentral/profile/authors/17283053tag:es.mathworks.com,2005:Question/6020862020-09-29T18:06:43Z2020-09-29T18:16:08ZHow do I find and store my amplitude values from seismic traces?Hi everyone,
I have a shot gather called gath1 (12x5001) where 12 is the number of traces and 5001 is time in ms. For each trace, I calculated the arrival times for the primeray reflection and the multiple. This arrival times are saved in a matrix called arr_bf1 with a size of 1x12x2. The first 1 is cause I extracted this values from a 3d matrix, it really doesnt do anything, 12 is the number of arrival times calculated, and the 2 is the reflector number. For example 1x12x1 are the 12 arrival times of my primary reflection, and 1x12x2 are the arrival times of my multiple. What I want to do is, for every trace in my supergather, extract the amplitude value at those arrival times. This would result in 2 amplitude values per trace. However, Ive tried to code it also using the findpeaks fucntion but get errors. Also, wanna store the amplitude of my primary reflections in one vector, and the amplitudes of my multiples in another vector (both would be 12x1).
Just for you all to know, I'm kinda new to Matlab so Im sure im doing several things wrong. If someone could help me, I would appreciate it.
This is my code:
%arrival times of best fit model
arr_bf1=times_test1(2,:,:); % This is a 1x12x2 matrix
%Extracts amplitudes from supergather based on arrival times of best fit model
gath1=gath1'; %gath1 is my shot gather with a size of 12x5001
pks1=zeros(12,1); %Stores the amplitudes of primary reflection
pks2=zeros(12,1); %Stores the amplitudes of multiple
for i=1:size(gath1,1)
pks1(i)= findpeaks(gath1(arr_bf1(:,i,1)));
pks2(i)= findpeaks(gath1(arr_bf1(:,i,1)));
end
I know it might be really simple but I can't put it together.
Thank you!Lucia Gonzalezhttps://es.mathworks.com/matlabcentral/profile/authors/14730199tag:es.mathworks.com,2005:Question/2546752015-11-13T16:13:19Z2020-09-29T18:15:46ZProbbaility Plot Uniform DistributionHi guys!!
i want to prove whether my test values behave like uniform distribution or not. Do you know if i can proove this with probplot? In documentation there are informations about normal etc. Or Is there another solution ?
cemsi888https://es.mathworks.com/matlabcentral/profile/authors/6090806tag:es.mathworks.com,2005:Question/6020832020-09-29T18:01:51Z2020-09-29T18:14:03ZEnd of Record (EOR) for splitter in TabularDatastoreHi
I have a large .csv file that I'm trying to analyse using datastore (called ds_mt) that is terminating after many read cycles.
while hasdata(ds_mt)
[dat,info] = read(ds_mt);
end
My understanding is that datastore splits the file into "splits" and will read through each split a "ReadSize" at a time until complete whereupon it loads a new split to continue the read cycle. The termination occurs trying to read the end of the 4th split. The file is a csv table with 29 fields/record and each record ends at the end of a line. However not every line in the file is the end of a record because some fields are multiple lines. The first 3 splits ended precisely at the end of a record but the 4th split ended at the end of a line but in the middle of field 27 of the record. This field was formatted as '%q' but was a 6 x 180 line array of numbers properly defined by a comma at the beginning and end. The termination occurred a line 44 of that field.
I know the file data is good because I can read through it using textscan (formatted for the 29 fields) and can load it into a spreadsheet.
I believe the splitter function is supposed to split at the end of record (EOR) but is using '\n\r' (end-of-line) instead of ',\n\r' (comma + end-of-line).
Can I fix it?
Thanks
Bob, (Matlab vers 16b)bob mcruerhttps://es.mathworks.com/matlabcentral/profile/authors/115340tag:es.mathworks.com,2005:Question/6018792020-09-29T11:10:41Z2020-09-29T18:12:07Zaveraging and interpolating random number of rows of dataHello, I have a list 800 particles data in an excel file. A total of 174755 rows...
Is there a way to extract these values and then average them based on their time point, later interpolate them based on the time point. I would like to average the first row of every particle 1,2,3....800. So after NaN, it will consider that as row 1,2,3...last number before NaN, then another row 1 again.
For example:
1 5
2 6
3 7
NaN
NaN
NaN
4 8
5 9
6 10
10 11
NaN
NaN
NaN
7 1
8 2
9 3
So the output average should be:
4 4.67
5 5.75
6 6.67
10 11
filename = 'plottemperature.xlsx';
T = xlsread(filename); %read excel file
[rows,columns] = size(T); %List the number of rows and columns
nanLocations = isnan(T); %declare all NaN locations in the excel file
for row = 1: rows
for col = 1:columns
if ~nanLocations(row,col) %I wanted to write it so that after the 3rd NaN it will be another row 1
%I am not sure how to continue from here to set the rows after every NaN as row 1 and then average all row 1
Please guide me. Thank you very much! Bryan Tanhttps://es.mathworks.com/matlabcentral/profile/authors/15037189tag:es.mathworks.com,2005:Question/6020892020-09-29T18:09:51Z2020-09-29T18:09:51ZHow Calculate R squared from a linear regressHey all I have this equation below and trying to figure out how to get the R^2.
I can't seem to understand what I am doing wrong.
x = 0:0.1:10;
n = 0;
noise = n*rand(1,length(x));
y = 2*x+1+noise; % y function
b = regress(y(:),[ones(size(x(:))),x(:)]); % get the intercept and slope
figure();
plot(x,y,'d') %plot as diamonds
hline = refline(b(2),b(1)); % plot the liner regresson line
hline.Color = 'r'; % change linear regresson line to red
I have looked at different ways in MATLAB but can't seem to understand.
Thank you.
Nicholas Deosaranhttps://es.mathworks.com/matlabcentral/profile/authors/19207774tag:es.mathworks.com,2005:Question/6020382020-09-29T16:01:34Z2020-09-29T18:08:34Zwhenever i use individual value of time (Tv) the output function (F) giving right value but using time in the form of loop ,output function gives wrong result for all.How to fix this ?clc
clear all
c1 = 3.742*10.^8;
c2 = 1.43878*10.^4;
sigma = 5.67*10.^-8;
lamda_1 = 8;
lamda_2 = 13;
Tv = -10:5:30;
F = zeros(size(Tv));
count = 1;
for T=Tv
fun = @(lambda) c1./(lambda.^5.*(exp(c2./(lambda * T+273)))-1);
F(count) = integral(fun,lamda_1,lamda_2)./(sigma.*(T+273)^4)
plot(T, F(count), '+', 'MarkerSize', 10, 'LineWidth', 2)
hold on
grid
count = count + 1;
end
xlabel('Temperature')
ylabel('Fraction in atmospheric window)')
title('Fraction of the radiation emitted in the atmospheric window as a function of temperature')
legend('T=-10','T=-5','T=0','T=5','T=10','T=15','T=20','T=25','T=30')
hold offSarvjeet Singhhttps://es.mathworks.com/matlabcentral/profile/authors/13298611tag:es.mathworks.com,2005:Question/6020802020-09-29T17:59:10Z2020-09-29T18:06:19ZAppend a row to a workspace tableI imported a table made in excel into MATLAB and it is now a table in my workspace. The Name is "Configuration" and it is a 1 x 20 table in my workspace. If you open up "Configuration" it looks like this:
>>
1 2 3 4 5 6 7
BookID State noofVols Vol_Interval VOL1 Vol2 Vol3
______ _______ ________ ____________ _______ _______ _______
NaN NaN NaN NaN NaN NaN NaN
>> disp(Configuration)
T2 = Configuration
W=width(T2)
BookID = 2;
State = ‘Open’;
noofVols = 2;
Vol_Interval = 4;
VOL1 = ‘BX2’;
Vol2 = “not used’;
Vol3 = ‘not used’;
appendRowVars = {BookID, State, noofVols, Vol_Interval, VOL1, Vol2, Vol3}
T2(end+1) = appendRowVars;
I am using MATLAB version 9.5.0.944444 (R2018b),. When I run this I get T2 = 1 x 7, W = 7, then I get an error message "Conversion to double frm cell is not possible"
Help
Jo Bremer Balestraccihttps://es.mathworks.com/matlabcentral/profile/authors/18684371tag:es.mathworks.com,2005:Question/353952012-04-13T14:19:49Z2020-09-29T18:01:18ZDistribution uniformity assessmentDear community,
I have a monochromatic image, in which some (same kind) objects are distributed. Ideally they should distribute evenly. However, they could be clumped.
How do I quantify the uniformity of the distribution? Any help will be greatly appreciated.
Xu
Xuhttps://es.mathworks.com/matlabcentral/profile/authors/3433669tag:es.mathworks.com,2005:Question/6020652020-09-29T17:12:02Z2020-09-29T17:55:50ZHow to make a function that graphs varying orders (ie 1st order, second order 3rd order)my original, very inefficient functions look like this:
Y2=X2(1)+ X2(2)*frequency + X2(3)*frequency.^2;
Y3=X3(1)+ X3(2)*frequency + X3(3)*frequency.^2 + X3(4)*frequency.^3;
Y4=X4(1)+ X4(2)*frequency + X4(3)*frequency.^2 + X4(4)*frequency.^3 + X4(5)*frequency.^4;
Y5=X5(1)+ X5(2)*frequency + X5(3)*frequency.^2 + X5(4)*frequency.^3 + X5(5)*frequency.^4 + X5(6)*frequency.^5;
(X# are the coefficients found using the function I have so far, which works perfectly)
I am using multiple functions and plots in this example but I only need to plot one at a time in practice. This is just to show what type of work I want matlab to do. So after the matlab function has done the matrix operations [input list(frequency in my example)] and [output list]
it will ouput a matrix of the coefficients depending on the selected order:
X =
2.0193
-0.8969
0.1664
-0.0121
0.0002
% 4th order in this case
which I would then have to graph with this:
plot(frequency,Y1)
plot(frequency,Y2)
assuming I have a matrix with the coefficients for the U order transfer function, to be graphed with input f, how do I write the "Y" or "plot( f , ? )" so that it will use whatever order function corresponds to the order U? so if U = 5 it will use the Y5 five coefficient function above but if U=3 it will use the Y3 three coefficient function? to clarify, I dont want to call to these Y# functions I used in my example, as I would have to write each one manually which would be bad, I am looking for a way to make a dynamic function that adds an
X(N)*f.^(N-1)
for every increment. its easy for me to visualize but I cant figure out how to turn this into code.
Update: I have attempted to make a summation that has a length based on the order number, but this causes indexing errors
j = [1:Order];
N = (1:(Order+1));
%T = X(N)*In.^(N-1);
syms n
Y = symsum(X(N(n))*In.^(N(n)-1),n,j(1),j(end))Reid Samshttps://es.mathworks.com/matlabcentral/profile/authors/16542106tag:es.mathworks.com,2005:Question/6020562020-09-29T16:43:54Z2020-09-29T17:46:49ZError using ^ (line 51) Incorrect dimensions for raising a matrix to a power. Check that the matrix is square and the power is a scalar. To perform elementwise matrix powers, use '.^'.Please help me to fix the problem mentioned as Error-1 and Error-2. I will be very thankful.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
clear all; close all; clc;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Simulation %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%value of constants
a=0.1;
omega=5;
dt=0.01; %step size
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
x(1)=1;
y(1)=1;
for i=2:1000
x(i)=x(i-1)+((a-x(i-1)^2-y(i-1)^2)*x(i-1)-omega*y(i-1))*dt;
y(i)=y(i-1)+((a-x(i-1)^2-y(i-1)^2)*y(i-1)+omega*x(i-1))*dt;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Observation %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Ndatamin=2;Ndatamax=7;
Data=Ndatamin:1:Ndatamax;
Data=Data/Ndatamax;
Error_x=zeros([1,Ndatamax-Ndatamin+1]);%initialization
count=0;
for N_m=Ndatamin:Ndatamax
count=count+1;
N_measurements=N_m;
N_basis=7;
index=randi([2,999],1,N_m);
HX=imag(hilbert(x));
Xdot=zeros([1,N_measurements]);
HXdot=zeros([1,N_measurements]);
for ni=1:N_measurements
Xdot(ni)=(x(index(ni)+1)-x(index(ni)))/dt;
HXdot(ni)=(HX(index(ni)+1)-HX(index(ni)))/dt;
end
M=zeros([N_measurements,N_basis]);
for i=1:N_measurements
for j=1:N_basis
if j==1
M(i,j)=1;
elseif j==2
M(i,j)=x(index(i));
elseif j==3
M(i,j)=HX(index(i));
elseif j==4
M(i,j)=x(index(i))*HX(index(i));
elseif j==5
M(i,j)=x(index(i))^2;
elseif j==6
M(i,j)=HX(index(i))^2;
else
M(i,j)=x(index(i))^2*HX(index(i))^2;
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% RIP %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Norms=zeros([1,N_basis]);
for j=1:N_basis
Norms(j)=norm(M(:,j));
end
for i=1:N_measurements
for j=1:N_basis
M(i,j)=M(i,j)/Norms(j);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Reconstruction %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
lambda=0.001;
Xdot=Xdot';
cd 'E:\MATLAB\bin\cvx\cvx'
cvx_setup
cvx_begin
variable ksaix(7);
minimize(norm(M*ksaix-Xdot)+ lambda*norm(ksaix,1));
cvx_end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
lambda=0.001;
HXdot=HXdot';
cd 'E:\MATLAB\bin\cvx\cvx'
cvx_setup
cvx_begin
variable ksaihx(7);
minimize(norm(M*ksaihx-HXdot)+ lambda*norm(ksaihx,1));
cvx_end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% RIP %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for j=1:N_basis
ksaix(j)=ksaix(j)/Norms(j);
ksaihx(j)=ksaihx(j)/Norms(j);
end
ksaix
ksaihx
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Reconstructed Equation %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
test_points=3;
start_point=500;
x_rec(1)=x(start_point);
x_real(1)=x(start_point);
hx(1)=y(start_point);
c1=ksaix(1);
c2=ksaix(2);
c3=ksaix(3);
c4=ksaix(4);
c5=ksaix(5);
c6=ksaix(6);
c7=ksaix(7);
d1=ksaihx(1);
d2=ksaihx(2);
d3=ksaihx(3);
d4=ksaihx(4);
d5=ksaihx(5);
d6=ksaihx(6);
d7=ksaihx(7);
error=0;
DN=0;
for i=2:test_points
x_rec(i)=c1+c2*x_rec(i-1)+c3*hx+c4*x_rec(i-1)*hx+c5*x_rec(i-1)^2+c6*hx^2+c7*x_rec(i-1)^2*hx^2;
hx(i)=d1+d2*x_rec(i-1)+d3*hx+d4*x_rec(i-1)*hx+d5*x_rec(i-1)^2+d6*hx^2+d7*x_rec(i-1)^2*hx^2;
x_real(i)=x(start_point+i-1);
error=error+(x_rec(i)-x_real(i))^2;
DN=DN+x_real(i)^2;
end
Error_x(count)=sqrt(error)/sqrt(DN);
end
figure
hold on
plot (Data,Error_x,'s-r')
plot (Data,hx(1:length(x)),'s-b')
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Error -1
Error using ^ (line 51)
Incorrect dimensions for raising a matrix to a power. Check that the matrix is square and the power is a scalar. To
perform elementwise matrix powers, use '.^'.
Error in PE_HT (line 125)
x_rec(i)=c1+c2*x_rec(i-1)+c3*hx+c4*x_rec(i-1)*hx+c5*x_rec(i-1)^2+c6*hx^2+c7*x_rec(i-1)^2*hx^2;
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Error -2 [When I replaced ^ with .^ then i get the error given below]
Unable to perform assignment because the left and right sides have a different number of elements.
Error in PE_HT (line 125)
x_rec(i)=c1+c2*x_rec(i-1)+c3*hx+c4*x_rec(i-1)*hx+c5*x_rec(i-1).^2+c6*hx.^2+c7*x_rec(i-1).^2*hx.^2;Heya :)https://es.mathworks.com/matlabcentral/profile/authors/9179792tag:es.mathworks.com,2005:Question/5988432020-09-24T03:06:51Z2020-09-29T17:44:19ZHow can use [c r p]=impixel('img1.png'); turn to an knowing [c r] to impixel imagefirstimage=imread('img1.png');
[c r p]=impixel(firstimage);
There is my question:
I can use the code above so for the first image I can get a value to impixel,
and now I want to use the same range,to do to the other,different case but same place,
so what I think is to get the first image [c r] value so I can write like this
impixel(firstimage c r)
so I can get the some range about it
but I have no idea how to get c value,because c is a double(matrix.....I think)
please help me about it,thanks
HUANG YU-CHEhttps://es.mathworks.com/matlabcentral/profile/authors/16249596tag:es.mathworks.com,2005:Question/6020742020-09-29T17:26:10Z2020-09-29T17:31:47ZHow to plot std::vector data from C++ program to figure window using Engine API for C++?This post is more a tutorial, sharing what I found that worked, than it is a question since I couldn't find a simple example to do the job. The task is simple:
Given two std::vector<double>:
std::vector<double> xvals;
std::vector<double> yvals;
representing x and y values for a sinusoidal function, use the Engine API for C++ to plot them to a figure window. I'm using Visual Studio 2019 and followed this tutorial verbatim [1] to install the headers and precompiled libraries to my VS project.
And the source code:
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
#include <numeric>
#include "MatlabEngine.hpp"
#include "MatlabDataArray.hpp"
using std::cout;
using std::vector;
using std::string;
using std::ofstream;
using std::ios_base;
class Sinewave
{
public:
vector<double> yvals;
vector<double> xvals;
// yvals = sin(a*t + b) and ownership of t is transferred to this object (as xvals) if it's an R-value
// a = angular frequency; the value resulting from 2*pi*f
// b = initial phase, in radians
Sinewave(double a, double b, vector<double>&& t): xvals(std::move(t))
{
yvals = vector<double>(xvals.size());
// Compute the angle values
std::transform(xvals.begin(), xvals.end(), yvals.begin(), [a, b](double xval) -> double {return a * xval + b; });
// Compute the sin-values
std::transform(yvals.begin(), yvals.end(), yvals.begin(), [](double angle) -> double {return sin(angle); });
}
// Transfer ownership of other SineSignal object's yvals, xvals
Sinewave(const Sinewave&& other) noexcept
: yvals(std::move(yvals)), xvals(std::move(xvals)) {}
// Output to csv file for quick plotting in matlab
bool ToCsvFile(const string path)
{
ofstream csvFile(path, ios_base::trunc);
if (!csvFile) return false; // Failure
vector<string> valPairs;
for (size_t i = 0; i < xvals.size(); i++)
{
std::stringstream ss;
ss << xvals[i] << "," << yvals[i] << '\n';
valPairs.push_back(ss.str());
}
for (auto pair : valPairs) csvFile << pair.c_str();
csvFile.close();
return true;
}
// Uses the Matlab Engine API for C++ to invoke Matlab's plot command and open a figure window
void PlotInMatlab()
{
std::unique_ptr<matlab::engine::MATLABEngine> MLPtr = matlab::engine::startMATLAB();
matlab::data::ArrayFactory factory;
// Create arguments for the call to Matlab's plot function
std::vector<matlab::data::Array> args({
factory.createArray({ xvals.size(), 1 }, xvals.begin(), xvals.end()),
factory.createArray({ yvals.size(), 1 }, yvals.begin(), yvals.end()),
factory.createCharArray(std::string("ro"))
});
// Invoke the plot command
MLPtr->feval(u"plot", args);
}
};
/* Returns multiples of Ts, the sampling period in seconds, beginning at tStart. */
vector<double> SampledTime(int nSamples, double Ts, double tStart = 0)
{
vector<double> tvals(nSamples);
std::iota(tvals.begin(), tvals.end(), tStart);
std::transform(tvals.begin(), tvals.end(), tvals.begin(), [Ts](double sampleVal) -> double {return sampleVal * Ts; });
return tvals;
}
int main()
{
double fs = 300; // Sampling frequency, in Hz
int nCycles = 2, nSamples = (int)((double)nCycles * fs); // Number of sine-wave cycles
vector<double> tvals = SampledTime(nSamples, 1 / fs);
const double pi = 3.141592653589793;
double w = 2 * pi * 1, poff = pi; // 1 Hz sinewave, 180 deg. out of phase
auto sw = Sinewave(w, poff, std::move(tvals));
sw.PlotInMatlab();
}
In main(), you define the sinusoidal parameters and use the SampledTime() method to get a sequence of time values (i.e., nT where n = 0, 1, ..., N and T is your sampling period). The sinusoidal angular frequency is given by w, the phase offset by poff. Then create a Sinewave object, passing in those sinusoidal parameters, which will then use cmath's sin() function to find the corresponding sin values. Call Sinewave.PlotInMatlab() and a figure window pops up with the sinwave plotted.
Since it's written in C++, you can change the sinewave parameters at runtime (i.e., prompt user for new sinuisoidal parameters), and have the program regenerate the plot. This to avoid writing the vector<double> data to file and then manually opening ML and manually invoking the matlab's plot command.
There's no good reason why Sinewave(double a, double b, vector<double>&& t) takes an R-value type as a third parameter. This was initially an experiment to see if using R-Value avoids copying the tvals array, which could potentially store a lot of doubles. I'm also playing around with move constructors, which is what
Sinewave(const Sinewave&& other) noexcept
: yvals(std::move(yvals)), xvals(std::move(xvals)) {}
is all about.
Comments/suggestions appreciated!
[1] I also had to add "C:\Program Files\MATLAB\_<ver>_\extern\bin\win64" to User environment variable.
% OS: Windows 10 Home, 64-bit
% IDE: Visual Studio Community 2019Minh Tranhttps://es.mathworks.com/matlabcentral/profile/authors/6735845tag:es.mathworks.com,2005:Question/6020442020-09-29T16:25:37Z2020-09-29T17:28:24ZSolving Maxwell Equations in a single dimension of spaceHello!
I have made the following simplifications to a system of PDEs and I was hoping to get some help as to how to format them for use in Matlab's pdepe command.
(d here is the partial derivative operator)
dE/dx + dB/dt = 0
and
dB/dX = 0
I am only solving in a single x dimension and in time. My initial condition are two Gaussian pulses for E and B. lpott005https://es.mathworks.com/matlabcentral/profile/authors/10569627tag:es.mathworks.com,2005:Question/6018132020-09-29T08:48:29Z2020-09-29T17:26:10ZHow to Contact File Exchange Admin?I try to update a FEX submission, but
The previous version is a zip-file and now I try to replace that with a mltbx-file. per isaksonhttps://es.mathworks.com/matlabcentral/profile/authors/1670tag:es.mathworks.com,2005:Question/3671812017-11-15T11:26:27Z2020-09-29T17:21:54ZCannot progress in matlab fundamentals course - matlab academy fails to communicate with workers and closes every time.Hi,
I have been working through the MATLAB fundamentals course on matlab academy and have reached a stage I cannot progress. Every time I submit on 5.12 task 3 matlab fails to communicate with the server (using diagnostic tools the following worker never responds: https://workerrouter-prodb-useast1.mathworks.com/messageservice/async?routingkey=10.97.36.168:8001) and the only solution is to restart in a different session.
I have tried on multiple machines and multiple browsers to no avail.
Any suggestions would be appreciated.Samhttps://es.mathworks.com/matlabcentral/profile/authors/8175765tag:es.mathworks.com,2005:Question/6020712020-09-29T17:17:42Z2020-09-29T17:21:47Zcorrecting non uniform intensity to uniformHi,
I would like to know how to correct the non uniform intensities in the image to uniform one ??. Attached the image here...Turbulence Analysishttps://es.mathworks.com/matlabcentral/profile/authors/19143687tag:es.mathworks.com,2005:Question/6020502020-09-29T16:30:31Z2020-09-29T17:14:23ZHow to get a matrix of all possible combinations that does not repeat.I want to get a matrix of all possible combinations, where the combinations does not repeat, for example the matrix should be [ 00 01 11] instead of [00 01 10 11] since 01 and 10 are the same.Mohannad Alzardhttps://es.mathworks.com/matlabcentral/profile/authors/9401116tag:es.mathworks.com,2005:Question/6020682020-09-29T17:13:06Z2020-09-29T17:13:06ZAre the 64-bit dlls built to support a specific Visual Studio version?We use MATLAB analysis in our product that is built using C++. In the past we used VS2010 and the application we built used dlls and libs from MATLAB that worked fine with our application. But, in recent days we switched to VS2017 and the were using the same old dlls and the application would crash. Does this mean we need to switch to latest dlls from MATLAB? If so, are the dlls and libs built to support or built with a specific version of VS?
Abhishek Bichalhttps://es.mathworks.com/matlabcentral/profile/authors/15091482tag:es.mathworks.com,2005:Question/5998842020-09-25T14:35:18Z2020-09-29T17:10:15ZHow to replace two columns in a txt file?Dear All,
I have a txt file which contains strings and numerical columns. Here are some samples of this txt file:
3 'CHSTRSVC' 345.00 2 0.00 0.00 1 1 1.0269 -11.382 1
4 'ORRINGTN' 345.00 1 0.00 0.00 1 1 1.0191 -16.365 1
3146 'ORRINGTN' 345.00 1 0.00 0.00 1 1 1.0162 -13.797 1
3147 'ORRINGTN' 345.00 1 0.00 0.00 1 1 1.0179 -13.586 1
......
I want to replace the values in the last 2 columns with updated values, and save the updated values in the same txt file. So the txt file has only two columns updated. For example, in the first row, I want to replace 1.0269 with 0.9987 and -11.382 with -10.5634.
Is there a simple way to do it?
Thanks.
BensonBenson Gouhttps://es.mathworks.com/matlabcentral/profile/authors/4652929tag:es.mathworks.com,2005:Question/6020622020-09-29T17:08:43Z2020-09-29T17:08:43Zpx4 toolchain installation not verified by Matlab's configuration 2020bHello,
I am following the steps in https://www.mathworks.com/help/supportpkg/px4/ug/setup-cygwin-toolchain.html but when I get to configure the support package, it tells me that the installation can't be verified because it can't find the toolchain version: "\Intel was unexpected at this time". Has anyone had and solved this problem? I have tried doing the installation in a couple of different ways.
Thank you,Juan Tapiero Bernalhttps://es.mathworks.com/matlabcentral/profile/authors/19564961tag:es.mathworks.com,2005:Question/5986632020-09-23T18:12:18Z2020-09-29T17:08:21Z5G DMRS sequence generationThe sequence generation is described in the spec (TS 38.211 5.2.1) and is implemented in the MATLAB 5G Toolbox function nrPRBS. Starting on line 61, there is a block of code:
% If a subsequence was requested, extract the subsequence
if ~isscalar(n)
prbs = prbsInternal(end-n(2)+1:end);
else
prbs = prbsInternal;
end
I have two related questions, What is the reason for requesting a subsequence? How does the UE know where to look for this DMRS sequence?Bryan Ehlershttps://es.mathworks.com/matlabcentral/profile/authors/18993801tag:es.mathworks.com,2005:Question/5995752020-09-25T05:03:23Z2020-09-29T17:08:03Zread tiff image in parforHi,
Below is the code I am trying to run. I can only run it with for loop. I alwyas get an "Invalid TIFF file ID" error when trying to use parfor loop even I tried to use 1 worker. I am using Matlab 2020a.
filename = 'myfile.tif';
warning('off','all')
tstack = Tiff(filename);
[I,J] = size(tstack.read());
K = length(imfinfo(filename));
data = zeros(I,J,K);
data(:,:,1) = tstack.read();
parfor n = 2:100
disp(int2str(n));
tstack.setDirectory(n)
data(:,:,n) = tstack.read();
end
warning('on','all')Wenjie Lihttps://es.mathworks.com/matlabcentral/profile/authors/19461903tag:es.mathworks.com,2005:Question/6020142020-09-29T15:23:03Z2020-09-29T17:07:47ZWhat else can I do to speed up evaluation of this function?I'm working with a function which is being called many times as part of a fitting algorithm. So I want to optimize it and reduce the runtime as much as possible. What more can I do for this? This i what I have already done:
truncated the numerical integration with an anonymous function so that I don't integrate over the entire thing;
reduced the relative tolerance for integration of the anonymous function;
wrote code using scientific notation (e.g. 1e5 instead of 10^5);
Edit: all the variables passed to the function are scalars, with the exception of abs_coeff and photon_flux, which are function handles, and V which is an 1-D array.
Right now the runtime for the function is between 0.9 - 15s, depending on the variables. Any optimization advice is welcome, thanks!
function j_sol = Reichman_ntype(In_0, Ip_0, N, n_i, tau, L, epsilon, phi_b0, T, abs_coeff, photon_flux, V)
q = 1.602176565e-19; % Elementary charge [C]
k_B = 1.38064852e-23; % m^2 * kg / s^2 / K
epsilon_0 = 8.8541878128e-14; %F/cm
p0 = n_i^2/N; %hole conc in /cm^3
J_n = -In_0/1000 * (exp(q * V/(k_B * T)) - 1); % electron current in mA/cm^2
phi_b = phi_b0 - V; %barrier in V
J_0 = 1000 * q * p0 * L / tau; %saturation current, units: mC * cm^-6/cm^-3 * cm/s = mA/cm^2
A = Ip_0 + J_0 * exp (q*V/(k_B * T)); %mA/cm^2
W = sqrt(2 * epsilon * epsilon_0 * phi_b / (q * N)); %depletion layer width, units: cm
K = pi * k_B * T * n_i * W .* exp(q * V / (2*k_B*T)) ./ (4 * tau * phi_b);
% units: J * cm^-3 * cm / (s * V) = mA/cm^2
j_sol = integral(@(x) ...
J_n + Ip_0 * ((((-K + (K.^2 + 4 * A .* (Ip_0 + (J_0 + 1e3 * q * photon_flux(x) *...
(1 - exp(-abs_coeff(x)*1e7 .* W)/(1 + abs_coeff(x)*1e7 * L))))).^(1/2))./(2 * A)).^2) -1), ...
250 , 1500, 'ArrayValued', true, 'RelTol', 0.01, 'AbsTol', 0); %mA/cm^2
end
P.S. Parallelization is not an option since this function is being called in a parfor already.Radu Borshttps://es.mathworks.com/matlabcentral/profile/authors/14671944tag:es.mathworks.com,2005:Question/6020052020-09-29T15:11:04Z2020-09-29T17:06:15ZReading 64 bit wordsI have tried reading a binary file 64 bits at a time, and is not behaving as expecting.
I have a binary file with the word = 0xFAFAFAFA00010001, if I read it like this:
word = fread(fid,1,'uint64'), and look at hex2dec(word), the word is 0xFAFAFAFA00010000 (yes, one bit has been changed).
but if I read:
word_l = fread(fid,1,'uint64'); word_h = fread(fid,1,'uint64'), I get 0x00010001 as hex2dec(word_l) and 0xFAFAFAFA as hex2dec(word_h).
I do not know if the problem is on the read (don't think so), or the 64bit management (I think is here), but I tried doing this too:
a=hex2dec('FAFAFAFA');
b = hex2dec('00010001');
dec2hex(bitshift(a,32))
% Output is 0xFAFAFAFA00000000
dec2hex(b)
% Output is 0x00010001
dec2hex(bitor(bitshift(a,32),b))
% Output is 0xFAFAFAFA00010000
Is there an issue with matlab and numbers larger than 53 bits? 60 bits?Francesc Massanes Basihttps://es.mathworks.com/matlabcentral/profile/authors/14118801tag:es.mathworks.com,2005:Question/6020592020-09-29T17:05:15Z2020-09-29T17:05:15ZColor detecting with neural network MLPHow can I detect some colors in test images using neural network.
I know that first the MLP must be trained to recognize colors (something with a color database) and then how to test that trained MLP on test images.
I need step by step guidance to understand how to make this.
Thank you Oana Popescuhttps://es.mathworks.com/matlabcentral/profile/authors/15532656tag:es.mathworks.com,2005:Question/6000222020-09-25T18:16:39Z2020-09-29T16:52:02ZHow to access the data/values from mlreportgen.dom.Table?I cannot figure out the way to get/access the data/values from a mlreportgen.dom.Table.
Thank you for your help!
Johnhttps://es.mathworks.com/matlabcentral/profile/authors/15413829tag:es.mathworks.com,2005:Question/4900192019-11-08T16:35:01Z2020-09-29T16:49:33ZLegend error (does not display 'line' in legend box)If I simply plot using the below code
x=0:0.1:10;
>> figure; plot(x,sin(x))
>> legend('on')
>> hold on
>> scatter(x, cos(x))
The figure looks like the below figure. The legend shows no 'line' for the first graph. It shows only circle.
How can I fix this problem?
Sangmin Leehttps://es.mathworks.com/matlabcentral/profile/authors/15285627tag:es.mathworks.com,2005:Question/6000882020-09-25T21:11:36Z2020-09-29T16:46:56ZThe margin changed on second pageUsing the import mlreportgen.dom.* the report is OK with rpt.CurrentPageLayout.PageMargins. However, the margin changed by itself on second page (the content flows to the sedond page as it's going). Repeating the definition with margins did not correct it.
What's wrong did I do?
Johnhttps://es.mathworks.com/matlabcentral/profile/authors/15413829tag:es.mathworks.com,2005:Question/6020532020-09-29T16:41:20Z2020-09-29T16:42:53ZIm new to matlab when i print a varible there is alot of white space but i cant remember the command to remove it
eg
total =
1
what is the command to make this
total =
1
ThanksTristan Smythhttps://es.mathworks.com/matlabcentral/profile/authors/18754780tag:es.mathworks.com,2005:Question/6020322020-09-29T15:59:40Z2020-09-29T16:37:45Ztimetable retime error - input timetable must contain unique row timesHi all,
I'm having difficulties undertanding the error code that i am getting.
using the code as stated below, i am trying to retime the timetable value for every 15 minutes.
timetable = unique(timetable)
dt = minutes(15);
timetable = retime(timetable,'regular','linear','TimeStep',dt);
The timetable looks as displayed below...
The error code that i am getting is as following:
"Error using timetable/retime (line 140)
Input timetables must contain unique row times when synchronizing using 'linear'."
What may be the problem here, and how may i solve it?
thank you.Sehoon Changhttps://es.mathworks.com/matlabcentral/profile/authors/7980157tag:es.mathworks.com,2005:Question/6018732020-09-29T11:02:15Z2020-09-29T16:37:36Zbessel function derivatives problemdear all
i have following equation that contain bessel function :
1- u(r)=j1(r) [1 mean the order and r is Variable(sysm)]
2-w(r)=j0(r)+i0(r) [0 mean the order and r is Variable(sysm)]
i need the the first derivative of the first equation (1 u(r) ) and second derivative of the second equation (2 w(r) )
is there any direct code for this purpose ?
thank a lot for your helps shahin hashemihttps://es.mathworks.com/matlabcentral/profile/authors/11613864tag:es.mathworks.com,2005:Question/5495642020-06-16T22:09:40Z2020-09-29T16:34:11ZHow do I build a driver application for a C++ MATLAB Data API Shared Library using Microsoft Visual Studio?The easiest way to build a driver application for a C++ MATLAB Data API Shared Library is by using mbuild. The mbuild utility accepts options that relate to your filesystem (such as the location of the header files you want to include and the libraries you want to link in), and chooses the best default values for the settings you omit.
However, you may wish to use Microsoft Visual Studio on Windows to build your driver application. What are the best settings to use?Alan Frankelhttps://es.mathworks.com/matlabcentral/profile/authors/3511363tag:es.mathworks.com,2005:Question/5989002020-09-24T05:55:49Z2020-09-29T16:33:38ZIndex exceeds the number of array elements.I am trying to solve this problem
Real sequence: x(m), x(m+1),…., x(n)
Reconstructed sequence: x(m), xrec(m+1),…xrec(n)
x(i)=x(i-1)+((a-x(i-1)^2-y(i-1)^2)*x(i-1)-omega*y(i-1))*dt;
x_rec=c1+c2*x_rec+c3*x_rec^2+c4*x_rec^3+c5*x_rec^4+c6*x_rec^5+c7*x_rec^6+c8*x_rec^7+c9*x_rec^8+c10*x_rec^9+c11*x_rec^10+c12*x_rec^11+c13*x_rec^12+c14*x_rec^13+c15*x_rec^14+c16*x_rec^15;
where c1 to c16= 1 to 16.
m=21, n=105
Error x = x(i)-x_rec(i))^2/x(i)^2;
***Facing these issues***
(Index exceeds the number of array elements (1).
Error in Untitled_new (line 152)
Error_x(count)=Error_x(count)+(x(i)-x_rec(i))^2;)
2. Also someone can please elaborate how to take real and reconstructed sequence as shown in MATLAB
Heya :)https://es.mathworks.com/matlabcentral/profile/authors/9179792tag:es.mathworks.com,2005:Question/3569272017-09-16T00:54:51Z2020-09-29T16:31:02ZHow to do the DoubleDown function? function finalValue = DoubleDown( initialValue )
% Complete the function to return twice the initialValue
finalValue = 0;
%supposed to make finalValue = 10 and then 240
end
<<https://www.mathworks.com/matlabcentral/answers/uploaded_files/88183/image.png>>Blair Hallhttps://es.mathworks.com/matlabcentral/profile/authors/10774882tag:es.mathworks.com,2005:Question/6018432020-09-29T09:47:44Z2020-09-29T16:27:55ZHow can I write summationn constraints for an optimization problem? Good morning,
I would like to optimize the following equation:
min
with the following contraints:
x>0
Where is a known set of values, is equal to a [288x1] vector and is also known as a [288x1] vector.
How can I add those constraints? I am trying to use x=fmincon(fun,x0,A,b,Aeq,beq);
Thanks! Ricardo Lópezhttps://es.mathworks.com/matlabcentral/profile/authors/14740625tag:es.mathworks.com,2005:Question/4512942019-03-20T22:47:52Z2020-09-29T16:23:58ZWhere does the compiler store any "files required for your application" such as a template Excel Workbook?I have a compiled application that copies template worksheets from a template workbook, and adds them to the user generated workbook. When I compile the program, the name of the template workbook shows up in he list of "Files Required for your Application". However, I do not see any Excel workbooks anywhere under Program Files where the application installs to. The program seems to run on my computer, but I am worried that may only be because it was developed on the computer. I worry that when I try to install this on other computers, the Excel workbook will not be found. Jim Brownhttps://es.mathworks.com/matlabcentral/profile/authors/4384612tag:es.mathworks.com,2005:Question/6017982020-09-29T08:19:47Z2020-09-29T16:23:50ZMultiple charts in the same windowI have seen that there is a way to make multiple charts in the same figure. I don't mean using subplot.
The result is a basic and slightly overlapping graph at the top, slightly external and smaller than another graph.
Do you know what the command is?Matteo Novellohttps://es.mathworks.com/matlabcentral/profile/authors/7808185tag:es.mathworks.com,2005:Question/6019872020-09-29T14:31:59Z2020-09-29T16:19:22ZHow do i make a uipanel with checkboxes return information to my script?Bottom line im trying to get my uifigure checkboxes to create a logical vector(f) that consistis of zeroes or ones based on what checkboxes gets selected.
All the files needed to run the code is attached, the BoxChanged.m function changes the value of the checkbox depending on wheter or not the respective box is selected(i think)
further than that i cant seem to get tho, considering i dont know how to use this to display information.
this function creates vectors simulating a 6 dice dicethrow
function [result] = terning(d,ant)
%TERNING Playing a random number of same sided dice
% Creating a result vector for the played dice. Taking the inputs d and
% ant to determine what results we get when we play ant d-sided dice.
result = randi(d,1,ant);
end
here is the function creating checkboxes:
function [box] = hukboks(a,b,y,p)
%This funcion creates a Checkbox in uifigure p, where b is a placeholder
%for hom many boxes needs to be made, and a is a counter telling the
%function how many boxes has been made, y is a variable setting names for
%the boxes
%S is the size of the checkbox(big enough for 1 digit)
%v is the spacing in pixels for left to right of the figure
%h is the distance(in pixels) from the bottom of the figure to the row of
%checkboxes
v = 700.*(a/b);
h = 350;
s = 25;
n = num2str(y);
box = uicheckbox(p,'text',n,'Position',[v h s s],...
'ValueChangedFcn',@(box,event) BoxChanged(box));
end
this function checks the value of the checkboxes(if the changed or not)
function BoxChanged(bx)
%Determining what will happen when Checkboxes are selected
val = bx.Value;
if val
bx.Value = 1;
else
bx.Value = 0;
end
end
this is the script i made to try to create my output vector f
p = uifigure('Name','PLZ HELP','Position',[150 100 909 539]);
kastvektor = terning(6,6);
b = length(kastvektor);
f = zeros(1,b);
for a = 1:b
y = kastvektor(a);
if a == 1
box1 = hukboks(a,b,y,p);
end
if a == 2
box2 = hukboks(a,b,y,p);
end
if a == 3
box3 = hukboks(a,b,y,p);
end
if a == 4
box4 = hukboks(a,b,y,p);
end
if a == 5
box5 = hukboks(a,b,y,p);
end
if a == 6
box6 = hukboks(a,b,y,p);
end
end
As explained earlier im trying to convert the zeroes vector f to become a vector of ones and zeroes corresponding to inputs from my panel.
Attached is also how the panel may look with boxes 1 to 6 going from left to right
Please if you know anything or have tips let me know im kinda smashing my heasd against a wall here.
Tore Henriksen Eliassenhttps://es.mathworks.com/matlabcentral/profile/authors/19254765tag:es.mathworks.com,2005:Question/6020412020-09-29T16:18:15Z2020-09-29T16:18:15ZAdding legend for subplot when none of the subplots include all legend entriesHi folks, I am trying to create a subplot where the points are coloured by year, and the years have the same colour in each subplot. Through careful control of the colours I have been able to achieve this, but I only want one legend for the figure, and none of the subplots contain all the years. I cannot figure out (excuse the pun!) how to create just one legend that has all the years (2011-2016). I can easily position one legend at the bottom of the subplot, that's not the problem. Here is the code to make the figure with individual legends (which I don't want in the end) to show you what I mean, along with the code. Thank you!
st_colours=[0, 0.4470, 0.7410;0.8500, 0.3250, 0.0980; 0.9290, 0.6940, 0.1250; 0.4940, 0.1840, 0.5560; 0.4660, 0.6740, 0.1880; 0.3010, 0.7450, 0.9330; 0.6350, 0.0780, 0.1840];
figure15 = figure();
for m=1:12
subplot(4,3,m)
if m==1 || m==2 || m==3 || m==4 || m==5 || m==6 || m==8 || m==11 || m==12 %Month
for r=1:5 %The row this time
sc(m,r)=scatter(QQG_Amm3M_T_split(m).months.NOAA_ONI(r),QQG_Amm3M_T_split(m).months.mean_Tmelt(r),25,'filled');hold on;
end
end
if m==7 || m==9 || m==10
for r=1:4 %The row this time
sc(m,r)=scatter(QQG_Amm3M_T_split(m).months.NOAA_ONI(r),QQG_Amm3M_T_split(m).months.mean_Tmelt(r),25,'filled');hold on;
end
end
if m==11 || m==12
for r=1:5 %The row this time
sc(m,r).MarkerFaceColor=st_colours(r,:);
end
elseif m==1 || m==2 || m==3 || m==4 || m==5 || m==6 || m==8
for r=1:5 %The row this time
sc(m,r).MarkerFaceColor=st_colours(r+1,:);
end
else
for r=1:4 %The row this time
sc(m,r).MarkerFaceColor=st_colours(r+1,:);
end
end
legend(string(QQG_Amm3M_T_split(m).months.mean_Year));
title(Month_labels(m));
xlim([-2 2.5]);
ylim([0 1]);
end
Catrionahttps://es.mathworks.com/matlabcentral/profile/authors/3207236