https://jp.mathworks.com/matlabcentral/answers/questionsMATLAB Answers — 新規の質問2020-10-31T08:54:26Ztag:jp.mathworks.com,2005:Question/6312792020-10-30T10:49:27Z2020-10-31T08:54:26ZOptimising Nearest Neighbor ProgramHi Guys,
I am trying to optmimise this code so that it runs in under 10 seconds for N=20k.
It currently takes around 40 seconds to run.
I think that I need to vecotirse some or all of the loops so that the calculations are done at the same time, but I cannot figure out how to do it.
Any help would be much appreciated as we are learning from home with next to no support from the University.
Here is the code.
s = zeros(N,N);
for n = 1:3
for a = 1:N
count = 0;
for b=1:N
off=0;
if (pos(n,a)<=0.25 && pos(n,b) >= 0.75)
off=1;
elseif pos(n,a)>=0.75 && pos(n,b)<=0.25
off=-1;
end
s(a,b)=s(a,b)+(pos(n,a)-pos(n,b)+off)^2.0;
if n == 3
s(a,b)=sqrt(s(a,b));
end
end
end
end
match = zeros(1,N);
for a=1:N
mindist=1e10;
for c=1:N
if (a~=c)
mindist=min(s(a,c),mindist);
if (mindist==s(a,c))
match(a)=c;
end
end
end
endSamuel Leeneyhttps://jp.mathworks.com/matlabcentral/profile/authors/13903456tag:jp.mathworks.com,2005:Question/6319992020-10-31T05:55:33Z2020-10-31T08:47:00ZHow to plot step functions in MatlabI have a function involving
y=o for x<o;
y=exp(-x)*cos(x) for 0<x<2pi();
y=2*exp(-x)*cos(x) for x>2pi();
please help me to plot such a type of function in xy spaceSangani Prithvihttps://jp.mathworks.com/matlabcentral/profile/authors/19737102tag:jp.mathworks.com,2005:Question/6319492020-10-31T02:18:43Z2020-10-31T08:46:52ZDoubt in the Impulse integralI'm not get to resolve this equation, I don't know what is wrong...
I = @(Tc,t)(mdot.*(sqrt(((2.*y.*R_gas.*Tc)./(y - 1)).*(1 - ((Pe)/(Patm)).^((y - 1)/(y))))));
Q = dblquad(I,0,Tc,0,t);Maria Angélica Paganehttps://jp.mathworks.com/matlabcentral/profile/authors/19109603tag:jp.mathworks.com,2005:Question/6296232020-10-28T19:46:42Z2020-10-31T08:44:09ZHow to determine the value of CONSTANT by solving the system of equation numerically. (A is need to determine)function [sol1]=Dr_Noreen
global A gamma r b
A=?;
b=0.5;
gamma=pi/3;
r=0.5;
sol = bvpinit(linspace(0,7,61),[0 0 0 0 0 0]);
options=bvpset('RelTol',10^-7);
sol1 = bvp4c(@bvpexam2, @bcexam2, sol,options);
x1 = sol1.x;
y1 = sol1.y;
figure (1)
plot(x1,y1(2,:),'r','linewidth',1.5);
figure (2)
plot(x1,y1(6,:),'r','linewidth',1.5);
function res = bcexam2(y0, yinf)
res = [
y0(1);
y0(2)-1;
yinf(2)-b*sin(gamma);
y0(4);
y0(5);
yinf(6)-1];
end
function ysol = bvpexam2(~,y)
yy1 =-y(1)*y(3)+y(2)*y(2)-b*b*sin(gamma)*sin(gamma);
yy2=(-y(1)*y(6)+y(2)*y(5)+A);
ysol = [y(2)
y(3)
yy1
y(5)
y(6)
yy2
];
end
endCute Dollhttps://jp.mathworks.com/matlabcentral/profile/authors/5403319tag:jp.mathworks.com,2005:Question/6320392020-10-31T07:21:11Z2020-10-31T08:41:19Zvariable declaration for optimization hello,
I am writing a code where I need to declare two variables which will be used for optimization in further, i.e,
a,b -----> variable(a=complex, b=real)
x=h1*a^2+h2*b^2+h3;------>h1,h2,h3 are constants
x=objective of optimization problem
what will be the code to declare 'a' and 'b';?Soumili Senhttps://jp.mathworks.com/matlabcentral/profile/authors/19922466tag:jp.mathworks.com,2005:Question/6319292020-10-31T01:02:28Z2020-10-31T08:39:54ZVALID_DATE FUNCTION PROBLEM : Write a function called valid_date that takes three positive integer scalar inputs year, month, day. If these three represent a valid date, return a logical true, otherwise false...
function [valid] = valid_date(y,m,d)
if ~isscalar(y) || ~isscalar(m) || ~isscalar(d)
valid= false;
end
if m > 12
valid= false;
elseif d > 31
valid= false;
end
if mod(y,4)==0
valid= valid_date(y,2,29);
valid= true;
end
if mod(y,400)==0 && mod(y,100)==0
valid= valid_date(y,2,29);
valid=false;
end
if m== 1 || 3 || 5 || 7 || 8 || 10 || 12
if d== 31
valid= true;
end
elseif m== 4 || 6 || 9 || 11
if d== 31
valid= false;
end
elseif m== 2
if d>=30
valid= false;
end
end
Emirhan Bilgiçhttps://jp.mathworks.com/matlabcentral/profile/authors/20047169tag:jp.mathworks.com,2005:Question/6321042020-10-31T08:38:59Z2020-10-31T08:38:59ZError loading .stl file to POFACETS 4.1I am currently using POFACETS 4.1 to model an bistatic RCS for an Rectangular slab, which was exported from blender in .stl format. while I upload file to MATLAB POFACETS 4.1, It shows below error.
Rendering drawing...
Unrecognized function or variable 'v'.
Error in utilities>rndread (line 332)
vout = v'; % "
Error in utilities>ImportSTL_Callback (line 253)
[F, V, C] = rndread(fileloc);
Error in gui_mainfcn (line 95)
feval(varargin{:});
Error in utilities (line 59)
gui_mainfcn(gui_State, varargin{:});
Error while evaluating UIControl Callback.
Did anyone face this issue and can someone help me solve this issue?
ThanksRohit Mallampatihttps://jp.mathworks.com/matlabcentral/profile/authors/16273366tag:jp.mathworks.com,2005:Question/4161212018-08-24T15:39:48Z2020-10-31T08:38:17ZIn R2018a, How can I show the legend for only the visible lines?In 2018a, legend shows up with some greyed out when the plot object's visibility is set to off.
In 2013a, the behavior is different, The legend only has the entries for the plots which are visible.
Example code to reproduce the issue :
figure
legendstr = {};
plot(0,0,'ro-','Visible','off')
legendstr(end+1) = {'Line1'};
plot(1:100,randn(1,100),'ks-')
legendstr(end+1) = {'Line2'};
plot([1 100],[0.5 0.5],'ro-')
lh=legend(legendstr);
Vivek Srinivasanhttps://jp.mathworks.com/matlabcentral/profile/authors/13238032tag:jp.mathworks.com,2005:Question/6320242020-10-31T07:00:38Z2020-10-31T08:37:55ZImposing positive semi-definiteness and symmetry in fminconI am solving an optimization problem in which I need a covariance matrix as a result using fmincon. The fmincon on initial guess gives some result but it is not symmetric and positive semi-definite, hence I am not able to use matrix factorizations like cholcov. I need to split the covariance matrix into L and L' such that L*L'=covariance matrixRicha Katarehttps://jp.mathworks.com/matlabcentral/profile/authors/17531633tag:jp.mathworks.com,2005:Question/6320892020-10-31T08:01:57Z2020-10-31T08:37:42ZHow to convert a log file into a list of strings?I am wondering how can I convert a logfile into a list of strings.
Here are some examples of a log file that i am tasked to convert into a list of string:
146.204.224.152 - feest6811 [21/Jun/2019:15:45:24 -0700] "POST /incentivize HTTP/1.1" 302 4622
197.109.77.178 - kertzmann3129 [21/Jun/2019:15:45:25 -0700] "DELETE /virtual/solutions/target/web+services HTTP/2.0" 203 26554
Note: There are lot of this log files which I am required to convert into a list of string and above are just two of them.
The output should look like this:
host: 146.204.224.152
username: feest6811
time: 21/Jun/2019:15:45:24 -0700
request: POST /incentivize HTTP/1.1
host: 197.109.77.178
username: kertzmann3129
time: 21/Jun/2019:15:45:25 -0700
request: DELETE /virtual/solutions/target/web+services HTTP/2.0
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
The log files above are in a notepad file which is in .txt format which i named logfile.txt
So far, this is the progress that I have made and the code.
fileID = fopen('logfile.txt','r');
data = textscan(fileID,'%s %*[^\n]');
stringdata = string(data{:});
disp(stringdata);
fclose(fileID);
And, it didn't display what I needed.
Can anyone help me what is the exact code that I actually need in order to make the output exactly the same as I desire? Enlighten me also what things were wrong in my code so I could learn from it. Thank you very much. Your help will be verily appreciated. Christian Jubilee Nelson B. Aldehttps://jp.mathworks.com/matlabcentral/profile/authors/19083853tag:jp.mathworks.com,2005:Question/6320942020-10-31T08:06:02Z2020-10-31T08:24:05ZHELP ME PLEASE with this geometric meanhow can I make the geometric mean in a matrix of 20x15 with only the positive numbers?IANC Cristian Gabrielhttps://jp.mathworks.com/matlabcentral/profile/authors/19800831tag:jp.mathworks.com,2005:Question/6320992020-10-31T08:11:27Z2020-10-31T08:21:05ZsetVariable in simscape model through SimulationInput object( MATLAB web app server)Hi everyone,
I am trying to set the value of a parameter that stays inside of a simscape block, using a web app aplication that was deployed on the server using MATLAB web app server.
The documentation says that the following Simulink functions and classes are deployable:
Functions:
sim
start_simulink
Classes:
Simulink.SimulationInput and its method setVariable
Simulink.SimulationOutput
Simulink.SimulationData.Dataset
I am using setVariable which allow me to set variables for a simulation through SimulationInput object.
SimInp = SimInp.setVariable('Tetha',app.tethaSpinner.Value);
In this way, I can modify certain parameters of the model but when the parameter is inside a Simscape block (elecrical , multibody, etc...) I am not able to modify the parameter anymore.
This problem only happens when I have to configure the application for deployment on the server using:
SimInput=Simulink.SimulationInput('SpringDamper');
SimInput=simulink.compiler.configureForDeployment(SimInput)
So, I was wondering if the problem is that the method SetVariable does not works with Simscape's blocks but only with Simulink Classic blocks.
Any suggestion would be great
Thank you Mauricio Rafael Calderonhttps://jp.mathworks.com/matlabcentral/profile/authors/13667257tag:jp.mathworks.com,2005:Question/6320742020-10-31T07:45:35Z2020-10-31T08:21:04Zcount rows from column file and store in a new columnsomeone could help me to see how to make a column that increases in numbers according to the number of entries from a column file?
I have this matrix: A = [1,2,3,4,5 ; 5,5,5,5,5; 5,5,5,5,5; 5,5,5,5,5; 5,5,5,5,5 ] and i want to add new column with number of each file.
and add this column to an existing file .takezohttps://jp.mathworks.com/matlabcentral/profile/authors/20037477tag:jp.mathworks.com,2005:Question/6320692020-10-31T07:44:05Z2020-10-31T08:18:52ZMatlab - how to convert date format in example providedIn my code below I am unable to convert the date format in column 1 from dd/MM/yyyy to MM-dd-yyyy. How do I configure it correctly to stop seeing this error??
>> T = readtable("IGEv3.xlsx");
>> tday=T{2:end, 1};
>> tday=datestr(datenum(tday, 'dd-MM-yyyy'), 'MM-dd-yyyy')
Error using datetime/datenum
Too many input arguments.
olayinka olahttps://jp.mathworks.com/matlabcentral/profile/authors/19344375tag:jp.mathworks.com,2005:Question/6316192020-10-30T16:09:39Z2020-10-31T08:09:22ZHow to plot this on a graphhow do u plot this between 0 and 2
syms n x
F = symsum(1/factorial(n),n,1,5)DARREN O BRIENhttps://jp.mathworks.com/matlabcentral/profile/authors/19968405tag:jp.mathworks.com,2005:Question/6285382020-10-28T02:11:03Z2020-10-31T08:01:36ZUse fzero() to calculate x required to achieve V/F for every combination of V and F.
k = 0.9;
n5Cate mayhttps://jp.mathworks.com/matlabcentral/profile/authors/20029193tag:jp.mathworks.com,2005:Question/6279532020-10-27T16:14:56Z2020-10-31T08:01:08ZIm confused by Matlab's dontinuous-to-discrete conversion methods and how they workHello community
Recently, I have been working a lot with the transformation from the s-domain to the z-somain using Matlab's c2d function. Currently I'm trying to get an overview about the different discretization methods, i.e. how do they work and when to use them. I'm confused by the notation Matlab uses compared to other literature. Everything I am asking is related to this documentation.
All I am interested in are transfer functions in the continuous-time and discrete-time domain. Meaning that given a transfer function , which steps do I have to perform to get the transfer function . This is what I came up with so far:
Can someone help me complete this table?
Furthermore, there are some more questions associated to this topic
1) As far as I understood, not every transformation is a simple substitution of the variable . However, is it possible to give a general relationship between the transfer function in the s-domain and z-domain for all cases?
2) According to the documentation, zero-order hold and first-order hold are used best for good matching in the time dimain for "staircase" and "piecewise linear" inputs. I do not know what to do with this information, i.e. why would an analog system be driven by such signals. What is the connection here?
3) Zero-Pole Matching should be used for good matching in the frequency domain according to Matlab's documentation. However, other sources state that this is not the case. I link the related Wikipedia article here (more sources stating this are cited there). In my case I am interested in modelling analog audio components in the digital domain. Hence, precise matching of the frequency response is important. Now I am not sure whether Zero-Pole matching is a good method or not.
4) The Tustin approximation also yields good matching in the frequency domain according to the documentation. From a theoretical point of view this cannot be true in general since the whole frequency axis is wrapped around the unit circle in a non-linear matter, i.e. there must be frequency distortion. The documentation further introduces the concept of the prewrapper frequency, which allows to capture the dynamics of an analog system on a particular frequency. This all yields to the same question as above: If I want to copy the behaviour of an system with audio frequencies (0Hz - 20 kHz), is this method suitable or not?
5) One transformation which I could not find in Matlab is the backwards difference. This transformation is used e.g. in Simulink for the discrete-time derivative block (assuming that a derivative in the continuous domain has the ideal transfer function ). I'm not sure whether this substitution even es a real transformation since I was unable to find related literature. Somebody has more information about it?
6) Why can I not use some transformations for non-causal systems? For example, I want to converte an (ideal) continuous-time derivative:
s = tf('s');
Ts = 5; % Sampling period
Gs = s; % Continuous-time TF
Gz = c2d(Gs,Ts,'impulse'); % Discrete-time TF
This gives an error for any method except Tustin's approximation and Zero-Pole matching. I know that there are stability issues, i.e. a contunuous-time derivative is unstable per definition and some transformation map a stable analog system to an unstable discrete system. Is this the problem? And why can Tustin's methor or Zero-Pole mapping handle this?Dominik Hiltbrunnerhttps://jp.mathworks.com/matlabcentral/profile/authors/17621751tag:jp.mathworks.com,2005:Question/6006462020-09-27T09:35:56Z2020-10-31T07:58:02ZUnable to resolve the name audio.internal.visualizer.Filter.Hello!
I keep getting the following error when executing the script AudioSystemToolboxIntroMain.m that accopanies the webinar "Real-time Audio Processing for Algorithm Prototyping and Custom Measurements" (https://se.mathworks.com/videos/real-time-audio-processing-for-algorithm-prototyping-and-custom-measurements-121075.html):
(Executing RealTimeStreaming.m works.)
Unable to resolve the name audio.internal.visualizer.Filter.
Error in ThreeBandParamEQ/visualize (line 122)
obj.visualObj = audio.internal.visualizer.Filter(coeffs,...
Error in AudioSystemToolboxIntroMain (line 10)
visualize(eq)
I believe that I have all required toolboxes installed:
>> ver
-----------------------------------------------------------------------------------------------------
MATLAB Version: 9.9.0.1467703 (R2020b)
MATLAB License Number: XXX
Operating System: Mac OS X Version: 10.15.7 Build: 19H2
Java Version: Java 1.8.0_202-b08 with Oracle Corporation Java HotSpot(TM) 64-Bit Server VM mixed mode
-----------------------------------------------------------------------------------------------------
MATLAB Version 9.9 (R2020b)
Simulink Version 10.2 (R2020b)
Antenna Toolbox Version 4.3 (R2020b)
Audio Toolbox Version 2.3 (R2020b)
Computer Vision Toolbox Version 9.3 (R2020b)
Curve Fitting Toolbox Version 3.5.12 (R2020b)
DSP System Toolbox Version 9.11 (R2020b)
Image Acquisition Toolbox Version 6.3 (R2020b)
Image Processing Toolbox Version 11.2 (R2020b)
MATLAB Compiler Version 8.1 (R2020b)
MATLAB Compiler SDK Version 6.9 (R2020b)
Optimization Toolbox Version 9.0 (R2020b)
Phased Array System Toolbox Version 4.4 (R2020b)
Signal Processing Toolbox Version 8.5 (R2020b)
Statistics and Machine Learning Toolbox Version 12.0 (R2020b)
Symbolic Math Toolbox Version 8.6 (R2020b)
I've tried
rehash toolboxcache
and reverting pathdef.m without success.
Thanks!Jens Ahrenshttps://jp.mathworks.com/matlabcentral/profile/authors/8188203tag:jp.mathworks.com,2005:Question/6320792020-10-31T07:46:31Z2020-10-31T07:47:30ZFilling area between two curves.Question: Take two functions as input from the user and find the area enclosed between them. Also fill the area with a color of your choice and mark the intersection points.
Problem: The output graph( or plot) fills only half of the area it is supposed to fill for some functions like x^2 + 10 and -x^2 + 11 ( refer to output image added in attachments)
Please help me with this.
syms x
% symbolic functions
f1 = input("Enter a function => ");
f2 = input("Enter another function => ");
% variable functions
f1s = tostr(f1);
f2s = tostr(f2);
f1v = str2func(strcat("@(x) ",f1s));
f2v = str2func(strcat("@(x) ",f2s));
% Solutions
sol = double(solve(f1-f2, x));
absval = abs(f1-f2);
area = double(int(absval,min(sol),max(sol)))
% Graph
domain = [min(sol)-2, max(sol)+2];
G1 = ezplot(f1, domain);
set(G1, 'color', 'r')
hold on
G2 = ezplot(f2, domain);
set(G2, 'color', 'b')
hold on
legend("f1", "f2")
% Coloring
xv = linspace(min(sol), max(sol));
f1val = subs(f1, x, xv);
f2val = subs(f2, x, xv);
x = [xv, xv];
y = [f1val, f2val];
fill(x, y, 'm')
grid on
% Markers
for i = 1:length(sol)
plot(sol(i), f1v(sol(i)), 'k*')
hold on
end
% --------------------------functions----------------------------
function output = tostr(x)
output = string(x);
endChandramauli Shastrihttps://jp.mathworks.com/matlabcentral/profile/authors/19898407tag:jp.mathworks.com,2005:Question/6320842020-10-31T07:47:29Z2020-10-31T07:47:29ZMatlab IPC s function, pythonHello, i am new to Matlab and i am deseperate and i need this for my graduation project please help.
I need to make a IPC server using s function that communicates with a python IDE usingI IPC client also, anyone can tell me where i can learn to do this ?
i am working with SimCenter PreScan so that's why I need this for, thanks so much in advancethomas josephhttps://jp.mathworks.com/matlabcentral/profile/authors/10656616tag:jp.mathworks.com,2005:Question/1383012014-06-29T06:47:22Z2020-10-31T07:42:11ZPlot Bit error rate for DWT based OFDMI ve been trying to plot the Bit error rate vs Eb/No for DWT based ofdm but What i get is a straight line which of course means that the error rate does not change over the course of the signal strength which obviously should not be so.I am quiet sure I m wrong somewhere in the code.
Here is the code snippet for IDWT at transmission side:
%% Setup
% Define parameters.
M = 4; % Size of signal constellation
k = log2(M); % Number of bits per symbol
n = 10000; % Number of bits to process
nsamp = 1; % Oversampling rate
nFFT = 64; % fft size
nDSC = 32; % number of data subcarriers
nQAMsymPerOFDMSym = 32; % number of QAM symboles per OFDM symbol (same as the number of subcarriers)
EbNo = [-3:20]; % multiple Eb/N0 values
for ii = 1:length(EbNo)
%% Signal Source
% Create a binary data stream as a column vector.
x = randint(nQAMsymPerOFDMSym*n,1); % Random binary data stream
%% Bit-to-Symbol Mapping
% Convert the bits in x into k-bit symbols.
xsym = bi2de(reshape(x,k,length(x)/k).','left-msb');
%% Modulation
% Modulate using 16-QAM.
y = modulate(modem.qammod(M),xsym);
xF = reshape(y,k,length(y)/k).';% grouping into multiple symbol
xF1=zeros(size(xF));
xt = (idwt(xF,xF1,'haar')).';
%% Transmitted Signal
%% Channel
% Send signal over an AWGN channel.
%% Received Signal
[yF1,yF2] =dwt(xt,'haar');
S=[yF1,yF2];
%% Demodulation
% Demodulate signal using 16-QAM.
zsym = demodulate(modem.qamdemod(M),S);
zsym1=zsym.';
%% Symbol-to-Bit Mapping
% Undo the bit-to-symbol mapping performed earlier.
z1 = de2bi(zsym1,'left-msb'); % Convert integers to bits.
% Convert z from a matrix to a vector.
z = reshape(z1.',prod(size(z1)),1);
%% BER Computation
% Compare x and z to obtain the number of errors and
% the bit error rate.
[number_of_errors(ii),bit_error_rate(ii)] = biterr(x,z);
end
theoryBer = (1/2)*erfc(sqrt(10.^(EbNo/10)));
close all; figure
semilogy(EbNo,theoryBer,'bs-','LineWidth',2);
hold on
semilogy(EbNo,bit_error_rate,'mx-','LineWidth',2);
axis([-3 15 10^-5 1])
grid on
legend('Theory', 'Simulation');
xlabel('Eb/No, dB')
ylabel('Bit Error Rate')
title('Bit error probability curve for M-QAM using DWT based OFDM system in AWGN channel')
Here is the O/P (which i think is wrong/unexpected):
<</matlabcentral/answers/uploaded_files/14787/graph.bmp>>
I am so confused...Wonder where I m wrong.Chaitanyahttps://jp.mathworks.com/matlabcentral/profile/authors/5433185tag:jp.mathworks.com,2005:Question/6320642020-10-31T07:39:55Z2020-10-31T07:39:55ZScore calculation in Classification SVM using kernel function as polynomial (quadratic)How the prediction scores are calculated for the binary classification in the quadratic SVM (support vector machine) model, trained in the classification learner app.
For calculation of the score of a particular set of observations (x) manually I followed, the page. which is f(x)=Sum ( αj .yj .G(xj,x) ) + b, j=1 to n . α , y are the model parameters. b is the bias, n is the number of support vectors. G is the kernel function (1+xj.x)^2. I am not getting same results as obtained by using " [~ , score]=predict() ".
For calculating the score of a new observation set manually, I had first normalized the data set(x) using the Mu, and Sigma vectors given in the model.
Kuldip Nayakhttps://jp.mathworks.com/matlabcentral/profile/authors/20170769tag:jp.mathworks.com,2005:Question/6320592020-10-31T07:29:56Z2020-10-31T07:29:56ZM(1,:) = [0;KB(1)]; In'The left side size is 1x7 and the right side size is 2x1, so the value cannot be assigned'. What is the problem???Hf_fig = figure;
phi = 0: 15: 90;
heel = pi*phi/180;
B = 6.480;
T = [ 1.729 1.575 1.163 0.600 -0.012 -0.693 -1.354 ];
w = [ 0 1.122 1.979 2.595 2.945 2.874 2.539 ];
KB = [ 1.272 1.121 0.711 0.107 -0.625 -1.393 -2.108 ];
KM = [ 4.596 3.711 2.857 1.830 0.479 -0.869 -1.471 ];
set(Hf_fig, 'NumberTitle', 'off',...
'Name', 'B and M curves');
clf
x = -T.* sin(heel); y = T.*cos(heel) ; k = length(heel);
Bcenter(1,:) = [0 KB(1)];
M = zeros(2,k);
M(1,:) = [0 KB(1)];
f = max((B/0.8), (B^2/(12*T(1))+T(1)/2));
plot(station(1, :), station(2, :), 'b-')
axis([ -f/2 f/2 -T(1)/2 (f-T(1)/2) ])
axis('square'), axis('off')
hold on
text(-B/1.8, T(1)+0.25, 'W_0')
text( B/1.8, T(1)+0.25, 'L_0')
text(-B/13, KB(1), 'B') , text(0, KM(1)+0.3, 'M')
xl = x0(1) - B/1.5; yl = y0(1); xr = x0(1) + B/(1.8-1/10);
yr = y0(1);
plot([ xl xr ], [ yl yr ])
plot(0, KB(1), 'r*')
plot(0, KM(1), 'ko')
plot([ 0 0 ], [ KB(1) KM(1) ], 'c-.')
pause
for I = 2:k
xl = x0(l) - B*cos(heel(l))/(1.5+l/1.7);
yl = y0(l) - B*sin(heel(l))/(1.5+l/1.7);
xr = x0(l) + B*cos(heel(l))/(1.8-l/10);
yr = y0(l) + B*sin(heel(l))/(1.8-l/10);
plot([ xl xr ], [ yl yr ])
if l ~= 1
string = [ num2str(phi(l)) '^o' ];
text(xl, yl, string)
text(xr, yr, string)
end
Bcenter(:, l) = rotate(heel(l))*[ w(l); KB(l) ];
plot(Bcenter(1, l), Bcenter(2, l), 'r*')
M(:, l) = rotate(heel(l))*[ w(l); KM(l) ];
plot(M(1, l), M(2, l), 'ko')
plot([ Bcenter(1, l), M(1, l) ], [ Bcenter(2, l), M(2, l) ],...
'k--')
pause(1)
end
pause
Bx = 0: Bcenter(1, k)/50: Bcenter(1, k); % interpolation axis
By = spline(Bcenter(1, :), Bcenter(2, :), Bx);
plot(Bx, By, 'm-')
Mx = 0: M(1, k)/50: M(1, k);
My = spline(M(1, :), M(2, :), Mx);
plot(Mx, My, 'y-') , text(-B/1.5, 1.4*KM(1),...
'The M-curve is the evolute of the B-curve')
hold off
P1 = [ 0.000; 0.50 ]; P2 = [ 0.240; 0.50 ];
P3 = [ 0.240; 0.58]; P4 = [ 1.100; 1.00 ]; P5 = [ 1.787; 1.25 ];
P6 = [ 2.460; 1.50 ]; P7 = [ 2.902; 1.75 ]; P8 = [ 3.100; 2.00 ];
P9 = [ 3.176; 2.25 ]; P10 = [ 3.200; 2.50 ]; P11 = [ 3.218; 2.75 ];
P12 = [ 3.230; 3.00 ]; P13 = [ 3.230; 3.36 ]; P14 = [ 2.099; 3.425 ];
P15 = [ 0.000; 3.489 ];
starb = [ P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P14 P15 ];
port = [ -starb(1, :); starb(2, :) ];
port = fliplr(port);
function r = rotate(phi)
r = [ cos(phi) -sin(phi); sin(phi) cos(phi) ];
end
SUNGJIN KIMhttps://jp.mathworks.com/matlabcentral/profile/authors/16499864tag:jp.mathworks.com,2005:Question/6320542020-10-31T07:29:21Z2020-10-31T07:29:21Zimage processing based on discrete fourier transformsAfter performing inverse DFT on an RGB image, the colors are getting distorted and spread all over the background. How to prevent this from happening?Pskhttps://jp.mathworks.com/matlabcentral/profile/authors/13253512tag:jp.mathworks.com,2005:Question/6320492020-10-31T07:25:28Z2020-10-31T07:25:28ZHow to show equation or formula of Regression on matlab?how to show the regression formula used when i plot the data? I tried to use axes but they still don't appear. Please help me.
hypodd.reloc
clc;
clear all;
data = load('hypodd.reloc');
x = data(:,3); % Long
y = data(:,2); % Lat
z = data(:,4); % Depth
A = [x y ones(length(x),1)]; % independent variable
[cc,bint,r,rint,stats]= regress(z,A); % compile the regression formula
scatter3(x,y,z); % Plot hypocenter
hold on;
x_grid=119:0.05:120;
y_grid=-3.2:0.05:-2.2;
[XFIT, YFIT]=meshgrid(x_grid, y_grid);
AFIT=cc(1)*XFIT+cc(2)*YFIT+cc(3);
surf(XFIT,YFIT,AFIT);
colorbar
title('\fontsize{14} hypocenter cross section fault model');
legend('cross section model',1);
xlabel('Longitude')
ylabel('Latitude')
zlabel('Depth in Kilometers')Afifah Shabrinahttps://jp.mathworks.com/matlabcentral/profile/authors/20113620tag:jp.mathworks.com,2005:Question/6320442020-10-31T07:24:13Z2020-10-31T07:24:13ZFilter design for removing noise phaseI am trying to remove a signals phase using filter. The filtfilt function do non phase shift filtering. Is it possible remove 30degree phase from signal? Utpal Mozumderhttps://jp.mathworks.com/matlabcentral/profile/authors/17482621tag:jp.mathworks.com,2005:Question/6320342020-10-31T07:18:29Z2020-10-31T07:18:29Zcan you help me with this project. i need a matlab code"The thin plastic rod in Fig. S1.4 has length 2L and a uniform linear charge density λ. Find the electric field at point P. Where L = 12cm, d = 8cm, λ = 50pC/m"Duong Tranhttps://jp.mathworks.com/matlabcentral/profile/authors/20175117tag:jp.mathworks.com,2005:Question/6287182020-10-28T06:16:20Z2020-10-31T07:10:17ZHow to set every Data Cursor in each column in this Figure automatically?a = 1 : 10
b = 1.001 : 10.001
c = 1.002 : 10.002
a = [a;b;c];
a = a (:)';
cg = clustergram(a, 'Cluster', 'row', 'DisplayRange', ceil(max(abs(a))), 'ColumnPDist', 'chebychev', 'Linkage', 'complete', 'Colormap',colormap('jet'), 'DisplayRatio', 1/9)
plot(cg)
Then, I need click every column and set a Data Cursor. It's too boring,
Is there a way to set every Data Cursor in each column in a Figure automatically, not manually?
Thank you in advance!
Liu Ananiahhttps://jp.mathworks.com/matlabcentral/profile/authors/10371545tag:jp.mathworks.com,2005:Question/6320292020-10-31T07:07:36Z2020-10-31T07:07:36Zエラー 358;ライセンスがきれてmatlabを起動するときにエラーがでます
エラー 358: ライセンス ファイルの有効期限を過ぎています。このライセンスのアクティベーションを行うには、ライセンス ファイルの有効期限を将来の日付に設定しなければなりません。 凌平 加藤https://jp.mathworks.com/matlabcentral/profile/authors/18491336tag:jp.mathworks.com,2005:Question/6320092020-10-31T06:12:49Z2020-10-31T06:48:15ZAdding or subtracting the same number Hi, I have a array, for example, [0 0 0 0 ]
And I want each of them to be randomly adding 0.4 or subtracting 0.4
How do I do that?Yi Chuan Xiehttps://jp.mathworks.com/matlabcentral/profile/authors/17621512tag:jp.mathworks.com,2005:Question/5113552020-03-17T16:39:58Z2020-10-31T06:48:11ZRequest for neural codeHi everyone, I need a "neural network" code for Solving Partial Differential Equation, please send if possible.IRFAN UR RAHMANhttps://jp.mathworks.com/matlabcentral/profile/authors/15253598tag:jp.mathworks.com,2005:Question/6278532020-10-27T15:00:56Z2020-10-31T06:37:04Zhow to solve this error "Matrix dimensions must agree".i am trying to find the pulse transit time by subtracting the ppg peaks from the ecg peaks, but it keeps giving me the following error "Matrix dimensions must agree".
I used a combiniation of several codes from your webiste, and I adjust them according to my data.
Please help me
thank you
The following is the code:-
%% Process the Data to Make Measurements and Visualize Signals
% Scale the signal per the specifications of the ECG sensor
ECG_adj = ((((y./(2.^10))-0.5) .* 3.3)./ 1100) .* 1000;
% Filter the scaled signal using a Savitzky-Golay filter
ECG_data = sgolayfilt(ECG_adj, 7, 41);
t = 1:length(ECG_data);
[~,locs_Rwave] = findpeaks(ECG_data,'MinPeakHeight',0.35);
% Calculate the heart rate
myheartrate = 60 ./ (median(diff(locs_Rwave)) ./ 1000);
%Visualize the Raw Data and Measured Heart Rate
figure
hold on
plot(t,ECG_data);
plot(locs_Rwave,ECG_data(locs_Rwave),'rv','MarkerFaceColor','r');
grid on
%Adjust the plot to show 8 seconds worth of measurements
ylim([-1 2]);
xlim([0 8000]);
title(sprintf('Heart Rate = %f / min', myheartrate));
xlabel('Samples'); ylabel('Voltage(mV)')
legend('ECG signal','R-wave');
%% peaks of ppg
% Process the Data to Make Measurements and Visualize Signals
% Scale the signal per the specifications of the ECG sensor
PPG_adj = ((((z./(2.^10))-0.5) .* 3.3)./ 1100) .* 1000;
% Filter the scaled signal using a Savitzky-Golay filter
PPG_data = sgolayfilt(PPG_adj, 7, 41);
t1 = 1:length(PPG_data);
[~,locs_Rwave1] = findpeaks(PPG_data,'MinPeakHeight',0.35);
% Remove Edge Wave Data
figure
hold on
plot(t1,PPG_data);
plot(locs_Rwave1,PPG_data(locs_Rwave1),'rv','MarkerFaceColor','r');
grid on
%Adjust the plot to show 8 seconds worth of measurements
ylim([-1 2]);
xlim([0 8000]);
xlabel('Samples'); ylabel('Voltage(mV)')
legend('PPG signal','R-wave');
%% PTT
n = locs_Rwave1;
m = locs_Rwave;
ptt=(n - m);
figure,stairs(ptt);
title('PTT');
xlabel('ptt');
ylabel('time');eman aljawihttps://jp.mathworks.com/matlabcentral/profile/authors/13436776tag:jp.mathworks.com,2005:Question/6320192020-10-31T06:28:55Z2020-10-31T06:28:55ZHi, Is my commenting right if I have been a sampling rate of 20khz to plot and sample the signal x1 containing 3 amplitudeThat is fs and Ts i am referring toGafi Wasswahttps://jp.mathworks.com/matlabcentral/profile/authors/12361537tag:jp.mathworks.com,2005:Question/6319892020-10-31T05:01:42Z2020-10-31T06:27:05Zhow to separate the lat lon points into 3 polygon? Can anyone help me on this please?clc
clear all
file=load('D:\MATLAB\20190808_4450_95104\polygon\str_CNVdataex.mat');
fidout1=fopen('D:\MATLAB\20190808_4450_95104\polygon\all.cnv','w');
for k=1:length(file.str_CNV)
on2=file.str_CNV(k).Ori.Year;
sar2=file.str_CNV(k).Ori.Month;
udur2=file.str_CNV(k).Ori.Day;
tsag2=file.str_CNV(k).Ori.Hour;
min2=file.str_CNV(k).Ori.Minute;
sec2=file.str_CNV(k).Ori.Second;
lat2=str2double(file.str_CNV(k).Ori.Lat);
cns2=file.str_CNV(k).Ori.Cns;
lon2=str2double(file.str_CNV(k).Ori.Lon);
cew2=file.str_CNV(k).Ori.Cew;
dep2=str2double(file.str_CNV(k).Ori.Dep);
mag2=file.str_CNV(k).Ori.Mag;
gap2= str2double(file.str_CNV(k).Ori.Gap);
rms2=file.str_CNV(k).Ori.Rms;
%if lat2<=47.22 && lat2>=46.70 && lon2<=98.5 && lon2>=97.00
if lat2<=49 && lat2>=48 && lon2>=95 && lon2<=103 lat2<=47 && lat2>=45.5 && lon2>=95 && lon2<=103
% if lat2<=48 && lat2>=46 && lon2<=102 && lon2>=100 if lat2==47.27 && lon2==98.24 && lat2==47.00&& lon2==98.00 && lat2==46.00&& lon2==101 && lat2==45.75 && lon2==100.76;
% if lat2<=47.27 && lat2>=47.00 && lon2<=98.24 && lon2>=98.00 && lat2<=46.00 && lat2>=45.75 && lon2<=101.00 && lon2>=100.76
fprintf(fidout1,'%s%s%s %s%s %s %7.4f%s %8.4f%s %5.2f %s %3.0f %s\r\n',on2,sar2,udur2,tsag2,min2,sec2,lat2,cns2,lon2,cew2,dep2,mag2,gap2,rms2);
n=0;
for m=1:length(file.str_CNV(k).ARR);
sta=file.str_CNV(k).ARR(m).STA;
phase=file.str_CNV(k).ARR(m).Phase;
wei=file.str_CNV(k).ARR(m).Wgt;
ttime=file.str_CNV(k).ARR(m).TTime;
fprintf(fidout1,'%s%s%s %s',sta,phase,wei, ttime);
n=n+1;
if n==6
fprintf(fidout1,'\r\n');
n=0;
end
if m == length(file.str_CNV(k).ARR) && n<6 && n~=0
fprintf(fidout1,'\r\n');
end
end
fprintf(fidout1,'\r\n');
% end
% end
end
end
fprintf(fidout1,'\r\n'); % enter
Here is my script that reads my data and sort by box or rectangular shaped area. Now I would like to seperate these data (dataex.txt which includes data) following 3 area. The rectanugular area and the data included in the area should be divided into 3 sections by two obliguity or virtue lines.
49.5N/95E to 49.5N/103E 49N/95E to 47N/103E
49N/95E to 47N/103E 48N/95E to 45.5N/103E
48N/95E to 45.5N/103E 45N/95E to 45N/103 E
file=load('D:\MATLAB\polygon\str_CNVdataex.mat'); which is all data
and I would like two create following datas from the north, center, and south sections, respectively.
fidout1=fopen('D:\MATLAB\polygon\north.txt','w');
%fidout1=fopen('D:\MATLAB\polygon\center.txt','w');
%fidout1=fopen('D:\MATLAB\polygon\south.txt','w');Bujeehttps://jp.mathworks.com/matlabcentral/profile/authors/10088831tag:jp.mathworks.com,2005:Question/6320142020-10-31T06:23:04Z2020-10-31T06:24:13Zhow to clustering/segment binary image?
I need to find an algorithm that can segement following image as circled.
I think semantic segmentation probably can do it, but I dont have enough labeled data for training.
K-mean clustering wouldent work.
Also, since all three parts are connected, regionprop dont work either.
I am apperciate if anyone could suggest any approaches that can segement images as described above.Felixhttps://jp.mathworks.com/matlabcentral/profile/authors/9081958tag:jp.mathworks.com,2005:Question/6320042020-10-31T06:10:47Z2020-10-31T06:10:47ZUpper bound Issue in SimulinkHello everybody,
I have a question. I'm running the below code in SIMULINK, but Matlab shows this error: "Output 'V' has variable size but the upper bound is not specified; explicit upper bound must be provided."
Also, I wrote the Lambert-W version of this code, but I took the same error.
The final aim of this code is to plot the I-V curve of a PV module, which will be used in another section in Simulink. Thus this is the reason why I can't write this code in mfile format.
I appreciate any help you can provide.
function [Ipv,V,P] = fcn(Rs, Rh, Iph, Is, etta, Voc, Vt)
Voc=29.2;
Rs=0.2185;
Rh=93.0571;
Is=2.0722;
Iph=8.09;
etta=1.073;
Vt=1.23;
V=0:(Voc/100):Voc;
I=Iph; %initial guess
for n1=1:length(V)
for n2=1:20 %number of iteration
Vd= (V(n1)+I*Rs);
Id=Is*(exp((Vd)/(etta*Vt))-1);
Ip=Vd/Rh;
f=Iph-Id-Ip-I;
df=-1-((Is*Rs/Vt)*exp(Vd/(etta*Vt)))-(Rs/Rh);
I=I-f/df;
end
if I<0
I=0;
end
Ipv(n1)=I;
end
P=Ipv.*V;
endSadegh Esfandiarihttps://jp.mathworks.com/matlabcentral/profile/authors/14656194tag:jp.mathworks.com,2005:Question/3007332016-08-24T12:42:48Z2020-10-31T05:52:27ZFFT Analysis Tool in PowerguiI want to use the powergui block for fft analysis.I am measuring three phase signals using a current measurement block connected to a scope. After running the simulation , the powergui's fft analysis does not display anything and the name and input fields display '-Empty-'.
Can anyone please suggest a solution to this problem, urgently.Luke Perabohttps://jp.mathworks.com/matlabcentral/profile/authors/8064743tag:jp.mathworks.com,2005:Question/2285572015-07-06T07:40:42Z2020-10-31T05:52:24ZExperts of MATLAB, how did you learn? Any advice for beginner/intermediate users?The community is very helpful, yet I feel really powerless that I cannot find the appropriate way to code, nor find the problems with the codes I have written. I have read numerous books on MATLAB, mostly related with science and engineering applications.
Any advice to improve would be greatly appreciated.
Thanks.bio limhttps://jp.mathworks.com/matlabcentral/profile/authors/4500990tag:jp.mathworks.com,2005:Question/6319942020-10-31T05:28:19Z2020-10-31T05:52:09ZNOT SURE HOW TO DO B,C,D FEEL LIKE I DID A,B RIGHTThis is a snipit of my code so far
BEN MILLERhttps://jp.mathworks.com/matlabcentral/profile/authors/19298001tag:jp.mathworks.com,2005:Question/6260632020-10-26T04:26:19Z2020-10-31T05:48:01ZExpansion in a Fourier Series I created a code that is supposed to calculate a0, an, bn, and f(x), for some reason it won't work when I include cos(n*pi)=(-1)^n to cos(-n*pi)=cos(n*pi). I want these three rules to apply while the code is running cause it's need to calculate an and bn correctly. Below is the code I have so far can someone please help fix this code so I calculate for all four functions.
MatLab Code Below:
% Problem_1 the Fourier series of the function f(x)
% f(x)=0 -pi < x < 0
% f(x)=1 0 < x < pi
clear all;clc;
syms x n pi
% pi=3.14;
sum=0;
y=0 %function you want
y1=1
a0=1/pi*int(y,x,-pi,0)+1/pi*int(y1,x,0,pi)
% for n=1:50
%finding the coefficients
cos(n*pi)=(-1)^n
sin(pi*n)=0
cos(-n*pi)=cos(n*pi)
an=(1/pi)*int(y*cos(n*x),x,-pi,0)+(1/pi)*int(y1*cos(n*x),x,0,pi)
bn=(1/pi)*int(y*sin(n*x),x,-pi,0)+(1/pi)*int(y1*sin(n*x),x,0,pi)
sum=sum+(an*cos(n*x)+bn*sin(n*x))
% endAijalon Marshhttps://jp.mathworks.com/matlabcentral/profile/authors/20083696tag:jp.mathworks.com,2005:Question/6300332020-10-29T07:14:45Z2020-10-31T05:47:50ZStore different data types efficientlyHi all,
I have a dataset of company announcements. After parsing I end up with several variables for every announement, like the body text (string array), the company name (string), the announcement date (double), etc. Until now, I stored these variables for all documents in a large struct array ( I have 55000 documents, resulting in a huge struct array). Unfortunately, it takes very long to load this struct in the workspace. Additionally, Matlab gets very slow in this case. Do you have a recommendation how to solve this problem?
I would be very grateful for every hint.
Thank you!Moritz Scherrmannhttps://jp.mathworks.com/matlabcentral/profile/authors/15158267tag:jp.mathworks.com,2005:Question/5583762020-07-02T12:10:17Z2020-10-31T05:35:01ZHow to create an custom Reinforcement Learning Environment + DDPG agentHello,
i´m working on an Agent for a problem in the spectral domain. I want to dump frequencies in a spectrum in a way that the resulting spectrum is looking like a rect() function.
So i created the following Environment with a [3 1] continuous Observation and Actionspace as an abstract Version of the real Problem. The initial Observation is a rndm [3 1] vector with values between 0 and 2. The Actionspace is a [3 1] vector with values between -1 and 1. The reward function is maximal when every vector element equals a final vector like[1 1 1].
the Environment file looks like this:
classdef SimpleContinuousEnv < rl.env.MATLABEnvironment
%SIMPLETESTENV: Template for defining custom environment in MATLAB.
%% Properties (set properties' attributes accordingly)
properties
% Specify and initialize environment's necessary properties
MaxForce=1
% Reward for a good correlation between observation and
% targetfunction
RewardForGoodShaping = 10
% Penalty for a bad correlation beween observation and
% targetfunction
PenaltyForBadShaping = -10
end
properties
% Initialize system state
State = zeros(1,3)
end
properties(Access = protected)
% Initialize internal flag to indicate episode termination
IsDone = false
end
%% Necessary Methods
methods
% Contructor method creates an instance of the environment
% Change class name and constructor name accordingly
function this = SimpleContinuousEnv()
% Initialize Observation settings
ObservationInfo = rlNumericSpec([3 1],'UpperLimit',[5;5;5],'LowerLimit',[-5;-5;-5]);
ObservationInfo.Name = 'Test SpectraObs';
ObservationInfo.Description = '1D rndm Number Vector';
% Initialize Action settings
ActionInfo = rlNumericSpec([3 1],'UpperLimit',[1;1;1],'LowerLimit',[-1;-1;-1])
ActionInfo.Name = 'Attenuation Vector';
ActionInfo.Description = '1D Attenuation Vector';
% The following line implements built-in functions of RL env
this = this@rl.env.MATLABEnvironment(ObservationInfo,ActionInfo);
% Initialize property values and pre-compute necessary values
updateActionInfo(this);
end
% Apply system dynamics and simulates the environment with the
% given action for one step.
function [Observation,Reward,IsDone,LoggedSignals] = step(this,Action)
LoggedSignals = [];
% Get action
Force = getForce(this,Action);
Observation=this.State+Force;
% Update system states
this.State = Observation;
% Check terminal condition
parse=(Observation==[1 1 1]);
IsDone=all(ismember(parse,1));
this.IsDone=IsDone;
% Get reward
Reward = getReward(this,parse);
% (optional) use notifyEnvUpdated to signal that the
% environment has been updated (e.g. to update visualization)
notifyEnvUpdated(this);
end
% Reset environment to initial state and output initial observation
function InitialObservation = reset(this)
InitialObservation = double([randi([1 2]);randi([1 2]);randi([1 2])]);
this.State = InitialObservation;
% (optional) use notifyEnvUpdated to signal that the
% environment has been updated (e.g. to update visualization)
notifyEnvUpdated(this);
end
end
%% Optional Methods (set methods' attributes accordingly)
methods
% Helper methods to create the environment
% Discrete force 1 or 2
function force = getForce(this,action)
force = action;
end
% update the action info based
function updateActionInfo(this)
% this.ActionInfo.Elements = this.ActionInfo.Elements;
end
% Reward function
function Reward = getReward(this,parse)
if this.IsDone==1
Reward = sum(parse*this.RewardForGoodShaping);
else
Reward = sum(~parse*this.PenaltyForBadShaping);
end
end
% (optional) Properties validation through set methods
function set.State(this,state)
validateattributes(state,{'numeric'},{'finite','real','vector','numel',3},'','State');
this.State = double(state);
notifyEnvUpdated(this);
end
function set.RewardForGoodShaping(this,val)
validateattributes(val,{'numeric'},{'real','finite','scalar'},'','RewardForGoodShaping');
this.RewardForGoodShaping = val;
end
function set.PenaltyForBadShaping(this,val)
validateattributes(val,{'numeric'},{'real','finite','scalar'},'','PenaltyForBadShaping');
this.PenaltyForBadShaping = val;
end
end
methods (Access = protected)
% (optional) update visualization everytime the environment is updated
% (notifyEnvUpdated is called)
function envUpdatedCallback(this)
plot(this.State)
hold off
XLimMode = 'auto';
YLimMode = 'auto';
end
end
end
This Environment validates but when i start Training with the folowing DNN and Training Options:
%%
%Create the Agent: Deep Q-Network Agent
%A DQN agent approximates the long-term reward given observations and
%actions using a critiv value function represenntation. To create the
%critic, frist create a deep neural network with two inputs, the state and
%the action, and one output.
statePath = [
imageInputLayer([3 1], 'Normalization','none','Name','state')
fullyConnectedLayer(24,'Name','CriticStateFC1')
reluLayer('Name','CriticRelu1')
fullyConnectedLayer(24,'Name','CriticStateFC2')];
actionPath = [
imageInputLayer([3 1],'Normalization','none','Name','action')
fullyConnectedLayer(24,'Name','CriticActionFC1')];
commonPath = [
additionLayer(2,'Name','add')
reluLayer('Name','CriticCommonRelu')
fullyConnectedLayer(1,'Name','output')];
criticNetwork = layerGraph(statePath);
criticNetwork = addLayers(criticNetwork, actionPath);
criticNetwork = addLayers(criticNetwork, commonPath);
criticNetwork = connectLayers(criticNetwork,'CriticStateFC2','add/in1');
criticNetwork = connectLayers(criticNetwork,'CriticActionFC1','add/in2');
figure(1)
plot(criticNetwork)
%figure(2)
%hold on
%%
%Specify Options for the critic representation using
%rlRepresentationOptions
criticOpts = rlRepresentationOptions('LearnRate', 0.01, 'GradientThreshold',1, 'UseDevice',"gpu");
obsInfo=getObservationInfo(env);
actInfo=getActionInfo(env);
critic = rlQValueRepresentation(criticNetwork,obsInfo,actInfo,'Observation',{'state'},'Action',{'action'},criticOpts);
%%
%To Create a DDPG Agent with an Continuous action space.
actorNetwork = [
imageInputLayer([3 1],'Normalization','none','Name','state')
fullyConnectedLayer(3,'Name','action','BiasLearnRateFactor',1,'BiasInitializer','zeros','Bias',[0;0;0])];
actorOpts = rlRepresentationOptions('LearnRate',1e-04,'GradientThreshold',1);
actor = rlDeterministicActorRepresentation(actorNetwork,obsInfo,actInfo,'Observation',{'state'},'Action',{'action'},actorOpts);
%To create the DDPG agent, first specify the DDPG agent options using
%rlDDPGAgentoptions
agentOpts = rlDDPGAgentOptions(...
'SampleTime',1, ...
'TargetSmoothFactor',1e-3, ...
'ExperienceBufferLength',1e6, ...
'DiscountFactor',0.99, ...
'MiniBatchSize',32);
agentOpts.NoiseOptions.Variance = 0.3;
agentOpts.NoiseOptions.VarianceDecayRate = 1e-6;
%Then, create the DDPG Agent using the specified actor representation,
%critic representation and agent options.
agent = rlDDPGAgent(actor,critic,agentOpts);
trainOpts = rlTrainingOptions(...
'MaxEpisodes', 500, ...
'MaxStepsPerEpisode', 10, ...
'Verbose', true, ...
'Plots','training-progress',...
'StopTrainingCriteria','EpisodeCount',...
'StopTrainingValue',5);
i get a big error in the training process calculating the cumulative reward. Anyway there seem to be many problems in this code i can´t figure out completly using the given examples from the toolbox.
Error using rl.agent.AbstractPolicy/step (line 116)
Invalid input argument type or size such as observation, reward, isdone or loggedSignals.
Error in rl.env.MATLABEnvironment/simLoop (line 241)
action = step(policy,observation,reward,isdone);
Error in rl.env.MATLABEnvironment/simWithPolicyImpl (line 106)
[expcell{simCount},epinfo,siminfos{simCount}] = simLoop(env,policy,opts,simCount,usePCT);
Error in rl.env.AbstractEnv/simWithPolicy (line 70)
[experiences,varargout{1:(nargout-1)}] = simWithPolicyImpl(this,policy,opts,varargin{:});
Error in rl.task.SeriesTrainTask/runImpl (line 33)
[varargout{1},varargout{2}] = simWithPolicy(this.Env,this.Agent,simOpts);
Error in rl.task.Task/run (line 21)
[varargout{1:nargout}] = runImpl(this);
Error in rl.task.TaskSpec/internal_run (line 159)
[varargout{1:nargout}] = run(task);
Error in rl.task.TaskSpec/runDirect (line 163)
[this.Outputs{1:getNumOutputs(this)}] = internal_run(this);
Error in rl.task.TaskSpec/runScalarTask (line 187)
runDirect(this);
Error in rl.task.TaskSpec/run (line 69)
runScalarTask(task);
Error in rl.train.SeriesTrainer/run (line 24)
run(seriestaskspec);
Error in rl.train.TrainingManager/train (line 291)
run(trainer);
Error in rl.train.TrainingManager/run (line 160)
train(this);
Error in rl.agent.AbstractAgent/train (line 54)
TrainingStatistics = run(trainMgr);
Error in DQN_Agent_for_LaserSpectrum_optimization (line 124)
trainingStats = train(agent,env,trainOpts);
Caused by:
Error using rl.agent.AbstractPolicy/step (line 103)
Error setting property 'CumulativeReward' of class 'rl.util.EpisodeInfo'. Value must be a scalar.
So i have many questions. First how to fix this error?
Second is such an agent even possible if my system is doing its work in 1 timestep. Like getting the observation vector and then with choosing one action vector reaching maximum reward?
If Yes which kind of agent maybe the best?
Third: How can i scale up the example to a much bigger vector and how can i shrink the action space maybe with constraints?
Fourth: how can i define one action which is a 1D vector and than define the range each element of the vector can have?In my case i wld have a n x 1 vector and each element can be in the range between 0-35.
Fifth: If my model is fine in simulation, how can i create an agent which works with a "real" hardware environment? Do i ve to write the environment in a way that i coontrols the hardware? Is there an example how this may work?
Thanks in advance for the answers and sry for the very long question.
best regards
KaiKai Tybussekhttps://jp.mathworks.com/matlabcentral/profile/authors/17864142tag:jp.mathworks.com,2005:Question/6313942020-10-30T12:06:39Z2020-10-31T05:21:03ZProbability density function for a time series of pressure dataHello Everyone,
I need to plot the probability density function for the data attached. I also attach reference pictures from a journal article. I am expecting similar results for the data attached.
Kindly helpNaveen K Shttps://jp.mathworks.com/matlabcentral/profile/authors/12808808tag:jp.mathworks.com,2005:Question/6311592020-10-30T07:26:59Z2020-10-31T05:18:43ZFiltering noise from an audio signalHi,
I have an audio signal, and I have two plots in the freq domain, amp vs freq and pow vs freq. Graphs attached.Can someone please tell me how do I find out which is the noise frequency and which is the sound frequency.
Code used for the plot:
Amp plot:
frequency_noise1 = fft(samples_noise1);
L = size(samples_noise1,1);
Fn = freqeuncyS_noise1/2;
FTy = frequency_noise1/L;
Fv = (linspace(0, 1, L/2)*Fn)/1000; %converting to KHz
Iv = 1:numel(Fv); % to match the vector sizes of X and Y
plot(Fv, abs(FTy(Iv,:)));
xlim([0 15]); %show x lim 0-5, 0-10, 0-15
ylim([0 0.01]);
title('Music plot Freq vs Amplitude')
set(gca, 'fontsize', 16);
xlabel('Frequency(KHz)');
ylabel('Amplitude(arb)');
Pow plot:
frequency_noise1 = fft(samples_noise1);
numberOf_samples = length(samples_noise1); % number of samples
f = (0:numberOf_samples-1)*(freqeuncyS_noise1/numberOf_samples); % frequency range
power = abs(frequency_noise1).^2/numberOf_samples; % power of the DFT
plot(f,power)
xlabel('Frequency')
ylabel('Power')
And also which filter should I chose to filter out my noise frequencyAditi Goswamihttps://jp.mathworks.com/matlabcentral/profile/authors/19596607tag:jp.mathworks.com,2005:Question/4669712019-06-13T17:50:01Z2020-10-31T04:44:32ZIf else problem for yearWrite a function called valid_date that takes three positive integer scalar inputs year, month, day. If these three represent a valid date, return a logical true, otherwise false. The name of the output argument is valid. If any of the inputs is not a positive integer scalar, return false as well. Note that every year that is exactly divisible by 4 is a leap year, except for years that are exactly divisible by 100. However, years that are exactly divisible by 400 are also leap years. For example, the year 1900 was not leap year, but the year 2000 was.
valid = valid_date(2018,4,1)
valid = valid_date(2018,4,31)RAHUL ANTILhttps://jp.mathworks.com/matlabcentral/profile/authors/14839405tag:jp.mathworks.com,2005:Question/6319392020-10-31T01:31:49Z2020-10-31T04:30:07ZHow can i plot these problems in matlab?? I have x and y coordinate of node 3 and node 4 .2.The free vibration test is carried out on 2DOF building in shake table. The vibration response obtained from wireless accelerometer sensor both in x and y directions are attached for further data processing.
Write a code in MATLAB software to,
(a) Plot the time domain acceleration data
(b) Plot the frequency domain data
(c) Estimate the first two natural frequency of a structure.
i m beginner in matlab so please help.Prakash Chettrihttps://jp.mathworks.com/matlabcentral/profile/authors/19635246tag:jp.mathworks.com,2005:Question/6316842020-10-30T17:27:09Z2020-10-31T04:25:59Ztrignometric equation in matlabI want to solve a trignometric equation in three different ways but it gives different solution in each..
f = 500;
w = 2*pi*f;
v11 = sqrt(alpha1*w*w/(K11*w*w-alpha11));
v12 = sqrt(alpha2*w*w/(K12*w*w-alpha12));
%%% dimensionless parameter%%%
v = X*v12;
alpha = alpha2/alpha1;
B = v11/v12;
Y= w*H/v12;
Q1 = (sqrt(X^2-1))*tan(Y*sqrt(X^2-1)/X)-(alpha*sqrt(1-B^2*X^2));
Q2 = tan(Y*sqrt(X^2-1)/X)-(alpha*sqrt(1-B^2*X^2)/(sqrt(X^2-1)));
Q3 = (Y*sqrt(X^2-1)/X)-atan(alpha*sqrt(1-B^2*X^2)/(sqrt(X^2-1)));
solv1 =(vpasolve(Q1==0,X))
solv2 =(vpasolve(Q2==0,X))
solv3 =(vpasolve(Q3==0,X))Davinder Kumarhttps://jp.mathworks.com/matlabcentral/profile/authors/10523240tag:jp.mathworks.com,2005:Question/6268682020-10-26T19:20:57Z2020-10-31T04:18:48ZMicrosoft Visual Studio 2017 C++ compiler not recognized in Matlab R2019bAccording to Matlab R2019 documentation, microsoft visual studio 2017 can be used as C++ compiler. After installing microsoft visual studio 2017, the C++ compiler is found in matlab R2017b using the mex -setup C++ command but if I try the same with matlab R2019B, the compiler is not found....
Moreover, I see that : C:\Program Files\MATLAB\R2019b\bin\win64\mexopts does not contain winsdk-7.1_c.xml whereas C:\Program Files\MATLAB\R2017b\bin\win64\mexopts does ...
Do you know why the matlab R2019B mex compiler is not able to recognize Microsoft Visual Studio 2017 ?
Thanks!mathide luycxhttps://jp.mathworks.com/matlabcentral/profile/authors/5570572tag:jp.mathworks.com,2005:Question/6319842020-10-31T04:13:43Z2020-10-31T04:13:43ZWhy doesn't signal units propagate through blocks?I just started to use the "signal units" feature on Simulink signals then I found that it doesn't go through my model. For example, I expect a signal in "Nm" of the output of a product block which has inputs of signals in "N" and "m". But it doesn't happen.
Am I missing something?Proglethttps://jp.mathworks.com/matlabcentral/profile/authors/8485329tag:jp.mathworks.com,2005:Question/6317242020-10-30T18:21:29Z2020-10-31T03:45:19ZSolving equations in a for loop with changing variablesHi all,
Not very experienced with matlab and trying to solve for d, L, and H as a function of x changing. The assignment asks that for the first half of x, H=0.5 and d=1.9 but I haven't been able to figure out how to start the loop in the middle of those vectors. I hardcoded a little bit to try to troubleshoot my first line, but the loop skews my depth somehow. Any advice would be greatly appreciated!Samantha Andesonhttps://jp.mathworks.com/matlabcentral/profile/authors/12123506