https://se.mathworks.com/matlabcentral/answers/questionsMATLAB Answers — New Questions2021-03-03T03:17:21Ztag:se.mathworks.com,2005:Question/7609662021-03-02T22:45:21Z2021-03-03T03:17:21ZIteration of Ideal Gas LawHi,
How can I do the iteration for the follwoing Ideal Gas Law? I would like to use the Vn and get the Pn value and compare the Ln value to the L. When Ln and L are very close, it will stop the iteration. I would really appreciate your help.
P=101325;
R=8.314;
r=20*10^-6;
L=117*10^-6;
V=pi*r^2*L;
T=300;
n=(P*V)/(R*T);
% Iteration should start from here
Tn=300+273;
Pn=(n/V)*R*Tn;
stress=Pn;
E=69.22*10^9;
S=stress/E;
dL=S*L;
Ln=L+dL;
Vn=pi*r^2*Ln;Sohel Ranahttps://se.mathworks.com/matlabcentral/profile/authors/13777906tag:se.mathworks.com,2005:Question/7611062021-03-03T03:06:41Z2021-03-03T03:16:32ZCreating regenerative random numbers The code creates 10 random ellipses
N = 10;
for R = 1:N %for loop to repeat 10 times
t = linspace(0,2*pi); % t defined angle??? not sure
xc = randn; %defines one of axis as random
x = xc + randn*cos(t);
yc = randn;
y = yc + randn*sin(t);
plot(x,y)
patch(x,y,rand)
hold on %puts all ellipses on same graph
end
How do I add to the code to make it so that everytime i run this code i get the same graph with the same random numbers inputed?Emma Isabella Figueredohttps://se.mathworks.com/matlabcentral/profile/authors/21279170tag:se.mathworks.com,2005:Question/7611162021-03-03T03:09:00Z2021-03-03T03:15:39ZIndex exceeds the number of array elements (1).Hello I am getting the following error when running this function in MATLAB:
Index exceeds the number of array elements (1).
Error in hw6_1 (line 11)
err = min(abs(f(a)),abs(f(b)));
Thank you!!
function [root, A, B] = hw6_1(f, a, b, numsegs)
%f = function
%a = lower limit of the initial range
%b = upper limit of the intial range
%numsegs = number of subranges
%root=number of roots
%A=vector of lower limits
%B=vector of upper limits
A=a;
B=b;
tol = 0.001;
err = min(abs(f(a)),abs(f(b)));
while (err >= tol)
dx = (b-a)/numsegs;
for i = 1:numsegs
x = a + (i-1)*dx;
prod = f(x) * f(x+dx);
if (prod <= 0)
a = x; %identify new subrange
b = x+dx;
A=[A,a];
B=[B,b];
end
end
err = min(abs(f(a)),abs(f(b)));
end
if (abs(f(a)) < abs(f(b)))
root = a;
else
root = b;
endNiccole Theriaulthttps://se.mathworks.com/matlabcentral/profile/authors/14800007tag:se.mathworks.com,2005:Question/7610712021-03-03T01:45:57Z2021-03-03T03:13:56Zvalid indices for 'output' are restricted in parfor loopHi,
i have the following code:
for j= 1:100
SNR = list(j);
parfor i = 1:1000
tot = (j-1)*1000+i;
totallist(tot,1) = SNR;
output(tot,1) = awgn(input(tot,1),SNR);
end
end
tot is just the total counter of the full loop
so the full loop contains 100*1000 values.
But why is the output(tot,1) and totallist(tot,1) forbidden?
How can i do it on another way?soepblikhttps://se.mathworks.com/matlabcentral/profile/authors/5890089tag:se.mathworks.com,2005:Question/7470872021-02-16T16:19:33Z2021-03-03T03:12:38Zchange start point of plotHi how can I change the Jan to start at 0?
Nurul Ain Basirah Zakariahttps://se.mathworks.com/matlabcentral/profile/authors/19251717tag:se.mathworks.com,2005:Question/7610462021-03-03T00:54:17Z2021-03-03T03:11:12ZHow generate a patch object with tetramesh?I have a triangulation object and I'm trying to create a patch from it using tetramesh, but once I use tetramesh it gives me double instead of patch. How can I get a patch from triangulation that is meshed with tetrahydrons?azarang asadihttps://se.mathworks.com/matlabcentral/profile/authors/16049273tag:se.mathworks.com,2005:Question/7610362021-03-03T00:48:44Z2021-03-03T03:10:50ZHow to get matlab to read the codeI have converted data from OnScale to matlab. I have been given a script which will read the data from this subfolder. The data loads in fine but I keep getting this error messages,
Error using load
Unable to read file 'C:\Users\User\Dropbox\My PC (LAPTOP-8G4JCC0U)\Documents\onscale1\2d_simple_array.mat'. No
such file or directory.
Error in example_import (line 15)
load(strcat('C:\Users\User\Dropbox\My PC
(LAPTOP-8G4JCC0U)\Documents\onscale',num2str(i),'\2d_simple_array.mat'));
All the files are in the same directory and folder as far as I can see, so maybe something needs changed in the code I have attahced screen shots of my code from line 15.
Thanks
David Harrahttps://se.mathworks.com/matlabcentral/profile/authors/20330617tag:se.mathworks.com,2005:Question/7611112021-03-03T03:07:43Z2021-03-03T03:07:43ZReaction kinetics parameter determinationHi, I am new to MATLAB and I have a series of data points to fit and then calculate the rate constants.
here are the equations:
dcdt(1)=-k(1)*c(1)-k(2)*c(1)-k(3)*c(1)
dcdt(2)=k(2)*c(1)-k(6)*c(2)-k(9)*c(2)
dcdt(3)=k(3)*c(1)-k(5)*c(4)-k(7)*c(6)
dcdt(4)=k(1)*c(1)-k(4)*c(4)-k(5)*c(4)
dcdt(5)=k(6)*c(2)+k(4)*c(4)-k(10)*c(5)
dcdt(6)=k(7)*c(3)-k(8)*c(6)
dcdt(7)=k(8)*c(6)+k(9)*c(2)+k(10)*c(5)-k(11)*c(8)-k(12)*c(9)
dcdt(8)=k(11)*c(7)
dcdt(9)=k(12)*c(8)
and the data:
Time=[0 2 4 10 15 25 40]
c= [100 0 0 0 0 0 0
0 4 37 15 5 4 2
0 10 20 8 4 0.2 0.1
0 5 10 16 4 2 1
0 4 5 11 5 4 3
0 5 6 5 1 0.1 0.04
0 6 12 32 64 44 31
0 0.0071 0.06 0.14 0.3000 3.8500 7.4440
0 0 0 0.0340 0.340 0.5000 0.630]
I would really appreciate the help! Thanks in advanceSurabhi Pandeyhttps://se.mathworks.com/matlabcentral/profile/authors/20411535tag:se.mathworks.com,2005:Question/7611012021-03-03T03:06:19Z2021-03-03T03:06:19ZIntegral Function inside while loop only works for certain values. ArrayValued results in empty volumn vectors.
I am having issues with the integral function only working for certain values of K.
I am looping through an interative summation where I calculate the nth solution of tan(L*z) = -K/h*z. The nth solution is a term in the functions defined by fun and fun2. If the value of K is set to 0.04, the program runs just fine. If I set the value of K to 20, the program throws the error
"Output of the function must be the same size as the input. If FUN is an array-valued integrand, set the 'ArrayValued' option to
true."
If I set the integral function to 'ArrayValued', true, then the code will run for the first iteration of the while loop, but in the second iteration the integral function will return an empty 0x1 vector.
while deltaW> 0.1 && n<1000
S= double(vpasolve(tan(L*z)== -K/h*z,z, [sol sol+pi/2/L]));
if isempty(S) ==1 %If empty reads false happens when there is a solution
sol = sol+pi/2/L;
S= vpasolve(tan(L*z)== -K/h*z,z, [sol sol+pi/2/L]);
sol=single(S);
end
lambdan=double(S);
sol = lambdan+0.01;
fun = @(x) ((Tinit-(T0 - h*(T0 - Tinf)/(K + h*L).*x))) .* sin(x.*lambdan);
fun2 = @(x) sin(x.*lambdan).^2;
anumerator = integral(fun,0,L);
adenominator = integral(fun2,0,L);
An = anumerator/adenominator;
Wn= An .* sin (lambdan.*x) .* exp(-lambdan.^2.*K.*time);
if n==1
W=Wn;
end
if n>1
deltaW = max(abs(W-Wn));
W=W+Wn;
end
n=n+1;
endGehn Fergusonhttps://se.mathworks.com/matlabcentral/profile/authors/21486522tag:se.mathworks.com,2005:Question/7610262021-03-03T00:35:57Z2021-03-03T03:03:08ZHow can I rotate an ellipse randomly This is what I have written so far
t = linspace(0,2*pi)
x = randn + randn*cos(t)
rng('shuffle');
y = randn + randn*sin(t);
plot(x,y)
I want to create random rotation for this ellipse each time I plot it while keeping this same code I have written so far. Emma Isabella Figueredohttps://se.mathworks.com/matlabcentral/profile/authors/21279170tag:se.mathworks.com,2005:Question/7590142021-03-01T03:17:26Z2021-03-03T02:59:59ZHow to fill the gaps on the boundary surface of the cone using MATLAB?Hi Mathworks community members
I am utilizing the Dr. Bruno Luong's code to fill the gaps. i am using P=[1 2 3; 8 0 4; 7 6 5] to fill the gaps on the boundary surface but some gaps cannot be filled successfuly. using this code, the gaps were filled as 3s. So, i need to adjust the P because its not filling all the gaps. Please anyone can guide me how to overcome this problem.
Aorg = load()
Aorg = s.Aorg;
gapmax = 10;
[m,n] = size(Aorg);
A = double(Aorg>0);
P=[1 2 3;
8 0 4;
7 6 5];
Apad = zeros(m+2,n+2);
maxattempt = 10;
for niter = 1:maxattempt
Apad(2:end-1,2:end-1) = A>0;
B = zeros(m,n,8);
for k=1:8
[i,j] = find(P==k);
B(:,:,k) = Apad(i-2+(2:end-1),j-2+(2:end-1));
end
As = A>0 & sum(diff(B(:,:,[1:8 1]),1,3)==1,3)<=1;
[y,x] = find(As);
if isempty(x)
break
end
p = length(x);
xy = [x,y];
xy1 = reshape(xy,1,[],2);
xy2 = reshape(xy,[],1,2);
d = sum(abs(xy1-xy2),3);
d(d==0) = NaN;
i = (1:size(d,1))';
[dmin,j] = min(d,[],2);
keep = dmin <= gapmax;
i = i(keep);
j = j(keep);
for k=1:length(i)
xyi = xy(i(k),:);
xyj = xy(j(k),:);
dxy = xyi-xyj;
if abs(dxy(1)) > abs(dxy(2))
xr = linspace(xyi(1),xyj(1),abs(dxy(1))+1);
yr = round(interp1([xyi(1),xyj(1)],[xyi(2),xyj(2)],xr));
else
yr = linspace(xyi(2),xyj(2),abs(dxy(2))+1);
xr = round(interp1([xyi(2),xyj(2)],[xyi(1),xyj(1)],yr));
end
A(sub2ind(size(A),yr(2:end-1),xr(2:end-1))) = 3;
end
endM.S. Khanhttps://se.mathworks.com/matlabcentral/profile/authors/13647580tag:se.mathworks.com,2005:Question/7610962021-03-03T02:56:43Z2021-03-03T02:56:43Zputting a trendline on a semi-log plot in MatLab.
The values are as following,
avgspeed = [27.7846701084929; 31.1385896602218; 33.3643634350556; 37.0654321948195; 38.5042712877777; 41.3807720015859] ;
height = [13; 33; 55; 155; 245; 519];
semilogy(avgspeed, height)
How do I code to find the equation of trendline for this semi-log plot?Shinichiro Shimatahttps://se.mathworks.com/matlabcentral/profile/authors/21378116tag:se.mathworks.com,2005:Question/7610312021-03-03T00:41:12Z2021-03-03T02:53:42ZPlot not generating graph
I have the below two functions and script below. I am trying to plot (a,ratio), but my graph is coming up blank?
Could someone please take a look at what Im doing wrong?
function [CL,CD] = CL_and_CD(a)
%CL_and_CD accepts alpha input,returns two outputs CL/CD
% Calculates the lift and drag co-efficients "CL" & "CD"
CL = (4.47*(10^-5*(a.^3))+(1.15*(10^-3)*(a.^2))+(6.66*(10^-2).*a)+1.02*(10^-1));
CD = (5.75*(10^-6*(a.^3))+5.09*(10^-4*(a.^2))+1.81*(10^-4.*a)+1.25*(10^-2));
end
function [ratio] = L_to_D(CL,CD)
%L_to_D accepts two inputs and returns one output
%Accepts inputs for CL & CD, and produces the Lift to Drag ratio.
ratio= CL/CD;
end
%Input
a=(-2:0.1:22);
%Call to function CL_and_CD
[CL,CD]=CL_and_CD(a);
%Call to function Ratio
[ratio]= L_to_D(CL,CD);
%Plot
plot(a,ratio);
xlabel('Angle of attack (\alpha)');
ylabel('Lift to Drag Ratio');
title('Lift to Drag Ratio by Angle of attack (\alpha)');
azaandriahttps://se.mathworks.com/matlabcentral/profile/authors/21301275tag:se.mathworks.com,2005:Question/7610912021-03-03T02:47:54Z2021-03-03T02:47:54ZUsing the Cancel button in uiprogressdlg to immediately stop executionI'm trying to get the cancel button in uiprogressdlg to stop execution immediately. I have a loop within which I check for CancelRequested == 1, but I'm only iterating that loop a few times. Each iteration has several steps with some pretty slow function calls (lots of data pulling and processing). Is there a way to get the cancel button to interrupt the execution of whatever is going on (kind of like a programmatic ctrl-c)? I check for CancelRequested == 1 after each step, but even then, I have to wait for the completion of a step which may take several minutes.Uday Patelhttps://se.mathworks.com/matlabcentral/profile/authors/1649572tag:se.mathworks.com,2005:Question/7601112021-03-02T08:10:08Z2021-03-03T02:47:13ZCan we apply scatter3() on high dimension matrix?Hi community members,
i have a matrix. i want to apply scatter3 . is it possible because usually we can apply on 3 colums.
is there any other function which we can apply to visulaize a matrix with respect to numbers.
A = [ 1 2 3 5 6 7 23 12 6;
3 4 4 4 23 17 22 45 12;
11 3 1 3 5 55 76 12 45 9;
- - - - - - - - --- --]
Regards,M.S. Khanhttps://se.mathworks.com/matlabcentral/profile/authors/13647580tag:se.mathworks.com,2005:Question/4684892019-06-23T17:41:32Z2021-03-03T02:45:49ZHow to implement Narma L2 on a plant?Hello. I want to implement Narma L2 controller on a two area power system but when i set the parameters to the plant identification window and browse for my plant a table shows with the message : You must enter a valid file name for your system. Can somebody help me with a simple example on how to implement Narma L2 on a system. I have seen the narmamaglev example but I still can not make the Plant identification recognize my plant. I don't have much experience with ANN and I would appreciate your advice and help.Rudens Marahttps://se.mathworks.com/matlabcentral/profile/authors/15628254tag:se.mathworks.com,2005:Question/537372012-11-14T21:38:13Z2021-03-03T02:43:17ZSave data before errorHi. I have run a MATLAB code and at the last step it faced with error. Running process takes me time about 7 days, so, I want to save available data until this step to the file. I could not see any data in workspace. Please let me know how can I save these data.
Cheers,jamaledinhttps://se.mathworks.com/matlabcentral/profile/authors/3754825tag:se.mathworks.com,2005:Question/7600312021-03-02T04:45:21Z2021-03-03T02:38:22Zdrawing a best fit graphis there a way to draw a best fit graph from a cut off circle, i have the [x y] coordinates for the first black points. now i want to use these coordinates to draw the exact shape on a graph. i tried polyfit but it doesnt give me the required shape
emeka onwocheihttps://se.mathworks.com/matlabcentral/profile/authors/21440672tag:se.mathworks.com,2005:Question/7610862021-03-03T02:28:59Z2021-03-03T02:34:33ZimportONNXLayers, importONNXNetwork, and importONNXFunction can't import my onnx model?As of March 3, 2021, importONNXLayers, importONNXNetwork, and importONNXFunction in the latest official version of onnx importer/exporter cannot import my onnx model?
My model link: R3D_50.onnx
Extraction code: kuni
net = importONNXLayers('R3D_50.onnx',...
'OutputLayerType','classification')
analyzeNetwork(net)
importONNXFunction ：
params = importONNXFunction('R3D_50.onnx',...
'resnet3D_50');
In both cases, the following internal errors occurred:
Error using nnet.internal.cnn.onnx.onnxmex
Invalid MEX-file
'C:\ProgramData\MATLAB\SupportPackages\R2020b\toolbox\nnet\supportpackages\onnx\+nnet\+internal\+cnn\+onnx\onnxmex.mexw64':
动态链接库(DLL)初始化例程失败。
Error in nnet.internal.cnn.onnx.ModelProto (line 31)
ModelPtr = onnxmex(int32(FuncName.EdeserializeFromFile), filename);
Error in nnet.internal.cnn.onnx.importONNXLayers (line 7)
modelProto =
nnet.internal.cnn.onnx.ModelProto(Filename);
Error in importONNXLayers (line 48)
Layers = nnet.internal.cnn.onnx.importONNXLayers(modelfile, varargin{:});
Error in testONNX2 (line 1)
net = importONNXLayers('D:\python_work\video_classification_pytorch\model\R3D_50.onnx',...
Error using nnet.internal.cnn.onnx.onnxmex
netron visual onnx model:
cuihttps://se.mathworks.com/matlabcentral/profile/authors/3388605tag:se.mathworks.com,2005:Question/977202009-07-07T19:09:00Z2021-03-03T02:23:05ZHow do I change the Temporary Directory that MATLAB uses?By default, MATLAB writes temporary files to /tmp/ on a LINUX system and the C:\Temp folder on a Windows System.
How can the MATLAB temporary directory be set to a different value? Can this be done at the system level, or by individual users in their MATLAB sessions?
MathWorks Support Teamhttps://se.mathworks.com/matlabcentral/profile/authors/4622813tag:se.mathworks.com,2005:Question/5028072020-01-30T15:03:42Z2021-03-03T02:20:36Zfinding best value for ARIMA (p,d,q) model?function ar = checkarma(y,pp,dd,qq)
LOGL = zeros(pp+1,dd+1,qq+1);
PQ = zeros(pp+1,dd+1,qq+1);
for p = 1:pp+1
for d = 1:dd+1
for q = 1:qq+1
mod = arima(p-1,d-1,q-1)
[fit,~,logL] = estimate(mod,y,'print',false);
LOGL(p,d,q) = logL;
PQ(p,d,q) = p+d+q;
end
end
end
LOGL = reshape(LOGL,(pp+1)*(qq+1)*(dd+1),1);
PQ = reshape(PQ,(pp+1)*(qq+1)*(dd+1),1);
[~,bic] = aicbic(LOGL,PQ+1,100);
ar = reshape(bic,pp+1,qq+1,dd+1);
Sir, i have a univariate time-series y having 10 values and i want to estimate optimum (p,d,q) values for ARIMA model.... it is giving error 'print is not a recongnized parameter'.ANURAG DEEPAKhttps://se.mathworks.com/matlabcentral/profile/authors/15510634tag:se.mathworks.com,2005:Question/7352972021-02-03T18:37:35Z2021-03-03T02:19:12ZArduino ESP32 stops posting to ThingSpeak after random times (error -301)The following code runs on an Adafruit ESP32 Feather that connects to the internet via my ASUS RT-N66U router. The ESP32 is "remote" and is accessible only via wifi.
It posts to ThingSpeak every 10 minutes and works fine for a day, sometimes a few days, but then it stops posting and returns error -301 ("failed to connect") with every attempt. It only starts posting again after a hard reboot.
I suspected heap fragmentation, but free heap is constant at 247k (after an initial quick decline from 250k) and max allocatable heap is constant at 114k from the start.
ESP32 hasn't lost wifi connectivity, since I can access the ESP32 via the router (and run the "server.on" commands).
I also have an ESP8266 posting to ThingSpeak every five minutes and it has been online for months, so the problem probably isn't with the router or ISP.
Even after the ESP32 stops posting, I can successfully manually post from a browser with https://api.thingspeak.com/update.json?api_key=xyz&field5=199, so it seems the problem is with the code.
I'm running the latest ThingSpeak library, ESP library and core (but not developmental version), and Arduino IDE.
Would appreciate suggestions on things to try or monitor.
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ArduinoOTA.h>
#include <ESP_Mail_Client.h>
#include <esp_int_wdt.h> // for hard reboot
#include <esp_task_wdt.h>// ditto
#include "ThingSpeak.h" // "always put this last in the list of includes"
WebServer server(80); // OTA and server.on
WiFiClient client; // TS only
//**** definitions etc ****
#define SMTP_HOST "smtp.gmail.com"
#define SMTP_PORT 465
#define AUTHOR_EMAIL "xyz@gmail.com"
#define AUTHOR_PASSWORD "abc"
SMTPSession smtp;
void smtpCallback(SMTP_Status status);
ESP_Mail_Session session;
SMTP_Message message;
const char * myWriteAPIKey = "efg"; // TS
const byte deltaDecreaseCM = 30; // threshold in cm... 12" = 30.48 cm
const int distAvg = 1060; // average distance
const unsigned long myChannelNumber = 123; // TS
bool paused = false;
bool savedPaused;
bool intruder = false;
bool alarmSounded = false;
bool snowing = false;
bool snowTriggeredOnce = false;
bool distSaving = true;
byte reqdNumBreaks = 6;
byte lastTSalarmFlag;
byte snowFactor = 1;
byte savedSnowFactor;
byte snowCount;
byte saveDist[100];
byte saveIdx = 99;
int distCurrent;
int savedDistance;
int lastTScode = 200;
int wiFiFailsTS;
unsigned long numIntruders; // can be very large if beam is blocked for a long time (eg. by parked car)
unsigned long alarmTriggeredTime;
unsigned long prevTSfailTime = 0;
unsigned long startSnowingTime;
unsigned long firstSnowTrigger;
unsigned long pauseStartTime;
unsigned long pauseDuration;
//**** setup ****
void setup()
{
Serial1.begin(115200); // TF03 default rate = 115200
WiFi.begin();
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
delay(5000);
ESP.restart();
}
setupMail();
server.on("/", handleRoot);
server.on("/reboot", reBootMe);
server.on("/postTS", doTSpost);
server.on("/showTS", showTScode);
server.onNotFound(handleNotFound);
ArduinoOTA.begin();
server.begin();
ThingSpeak.begin(client);
readTFxTimes(50); // clear serial1 buffer
}
//***************************************************************************************
//**** loop ****
//***************************************************************************************
void loop() {
ArduinoOTA.handle(); // this works even if posting to TS does not work
server.handleClient(); // ditto
unsigned long currTime = millis();
const unsigned long writeTSinterval = 600000UL; // post to TS every 10 min (and upon sounding alarm)
static unsigned long prevTSwriteTime = 0;
const unsigned long maxAlertInterval = 600000UL; // no duplicate alarms for 10 min after an alarm
// reset pause flag if time is up
if (paused && (currTime - pauseStartTime > pauseDuration)) {
paused = false;
}
// reset alarm flag if time is up
if (alarmSounded && (currTime - alarmTriggeredTime > maxAlertInterval)) {
alarmSounded = false;
}
readTFxTimes(1); // read TF03 once every loop
if (! paused && ! alarmSounded) { // chk for intruder, but only if not paused and not w/in 10 min of an alarm
chkForIntruder();
if (intruder && (numIntruders == reqdNumBreaks * snowFactor)) soundAlarm(); // sound alarm if sufficient number of sequential brks
}
// post to thingSpeak
if (prevTSfailTime) { // if an alarmFlag=1 write failed (posted too soon after an alarmFlag=0 post)
if (currTime - prevTSfailTime > 20000UL) { // try again after 20 sec (15.1 sec didn't seem to work on 1/27 when there was a collision)
prevTSfailTime = 0;
prevTSwriteTime = currTime;
writeThingSpeak(1, savedDistance, savedSnowFactor, savedPaused);
//this will only do one re-try. If this fails again with -401 (for whatever reason)
//it will just continue on with normal (alarmFlag=0) posts after 10 minutes.
}
} else if ((currTime - prevTSwriteTime > writeTSinterval) && (! intruder)) {
prevTSwriteTime = currTime;
writeThingSpeak(0, distCurrent, snowFactor, paused); // zero indicates no alarmFlag
}
}
//***************************************************************************************
//**** writeThingSpeak ****
//***************************************************************************************
void writeThingSpeak(byte alarmF, int distC, byte snowF, bool pausD) {
if (WiFi.status() != WL_CONNECTED) { // should already be connected, but check again anyway
wiFiFailsTS++; //this has never been > 1
while (WiFi.status() != WL_CONNECTED) {
WiFi.begin();
delay(5000);
}
}
int freeHeap = ESP.getFreeHeap();
int maxAllocatable = ESP.getMaxAllocHeap();
ThingSpeak.setField(1, distC);
ThingSpeak.setField(2, alarmF); // 0 = no intruder; 1 = intruder; 4 = manual test post
ThingSpeak.setField(3, snowF); // 1 = no snow; other = snowing
ThingSpeak.setField(4, pausD);
ThingSpeak.setField(5, lastTScode);
ThingSpeak.setField(6, freeHeap);
ThingSpeak.setField(7, maxAllocatable);
ThingSpeak.setField(8, wiFiFailsTS);
lastTScode = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
readTFxTimes(50); // in case the above takes "a while". 100 = about one second of reads, so 50 is about half a second
/*
https://github.com/mathworks/thingspeak-arduino
Return Codes
Value Meaning
200 OK / Success
404 Incorrect API key (or invalid ThingSpeak server address)
-101 Value is out of range or string is too long (> 255 characters)
-201 Invalid field number specified
-210 setField() was not called before writeFields()
-301 Failed to connect to ThingSpeak <-------------------------------
-302 Unexpected failure during write to ThingSpeak
-303 Unable to parse response
-304 Timeout waiting for server to respond
-401 Point was not inserted (most probable cause is the rate limit of once every 15 seconds)
0 Other error
*/
}
//**** chkForIntruder ****
void chkForIntruder() {
int deltaDist = distAvg - distCurrent;
if (distSaving) { // not currently accessible (deleted the associated server.on)
saveIdx = (saveIdx + 1) % 100;
if (deltaDist < 0) {
saveDist[saveIdx] = 0;
} else {
saveDist[saveIdx] = deltaDist;
}
}
if (deltaDist > deltaDecreaseCM) { // if distance descreases more than the limit, then there's an intruder
intruder = true;
numIntruders++; // number of sequential breaks, actually
} else {
if (snowing) {
if (millis() - startSnowingTime < 1800000UL) {
if ((reqdNumBreaks / 2 < numIntruders) && (numIntruders < reqdNumBreaks)) snowCount++;
} else { // time is up
if (! snowCount) { // if snowCount == 0, reset flag and factor
snowing = false;
snowFactor = 1;
} else { // snowCount was > 0, so need to keep checking...
startSnowingTime = millis(); // reset time, so check again later
snowCount = 0; // restart count for this new period
} // end "else" (snow count > 0)
} // end "else" (time is up)
} else { // end "if snowing"
if (snowTriggeredOnce) {
if (millis() - firstSnowTrigger > 300000UL) { // triggered once, but time expired, so re-set flag
snowTriggeredOnce = false;
} else if ((reqdNumBreaks / 2 < numIntruders) && (numIntruders < reqdNumBreaks)) { // triggered once, time not expired, meets criteria...set snowing flag, etc.
startSnowingTime = millis();
snowing = true;
snowFactor = 4;
snowTriggeredOnce = false;
distSaving = false;
} //end snowTriggeredOnce
} else if ((reqdNumBreaks / 2 < numIntruders) && (numIntruders < reqdNumBreaks)) { // not triggered yet, but meets criteria, so set triggered once flag, etc.
snowTriggeredOnce = true;
firstSnowTrigger = millis();
} // end not triggered yet but meets criteria
} // end "not snowing"
intruder = false;
numIntruders = 0;
} // end "else" distance not decreased...so no intruder, and numIntruders reset to zero
}
//**** soundAlarm ****
void soundAlarm() {
alarmTriggeredTime = millis();
alarmSounded = true;
sendMyMailNow(); //send an alert
if (snowing && (startSnowingTime - alarmTriggeredTime < 5000)) {
snowing = false;
snowFactor = 1;
}
writeThingSpeak(1, distCurrent, snowFactor, paused); // 1 indicates intruder
if (lastTScode == -401) {
prevTSfailTime = millis();
savedDistance = distCurrent;
savedSnowFactor = snowFactor;
savedPaused = paused;
}
}
//**** readTFxTimes ****
void readTFxTimes(byte numOfReads) {
for (byte i = 0; i < numOfReads; i++) {
while (! readTF03once()) { //read until a number is obtained
}
}
}
//**** readTF03once ****
bool readTF03once() {
int check; // checksum
byte uart[9]; // stores each byte of data returned by LiDAR (was int... I changed to byte)
const byte HEADER = 0x59; // data package frame header...the letter "Y" in ASCII (was int... I changed to byte)
if (Serial1.available()) { //check whether the serial port has data input
if (Serial1.read() == HEADER) { // determine data package frame header = 0x59
uart[0] = HEADER;
if (Serial1.read() == HEADER) { // determine data package frame header = 0x59
uart[1] = HEADER;
for (byte i = 2; i < 9; i++) { // store rest of data to array
uart[i] = Serial1.read();
}
check = uart[0] + uart[1] + uart[2] + uart[3] + uart[4] + uart[5] + uart[6] + uart[7];
if (uart[8] == (check & 0xff)) { // check the received data as per protocols 0xff = 0b11111111
// Not sure why bitwise and (&) is used.
distCurrent = uart[2] + uart[3] * 256; // calculate distance value
return true; //got a reading
}
}
}
}
distCurrent = 0;
return false; //didn't get a reading
}
void handleRoot() {
if (server.arg("pause") != "") { // i.e., if not zero, then user entered ...?pause=(a number)
paused = true;
pauseDuration = (unsigned long) server.arg("pause").toInt(); // in minutes
pauseStartTime = millis();
if (pauseDuration <= 0) { // if neg, do nothing
paused = false;
} else if (pauseDuration > 1200) { // if large, limit to 1200 minutes = 20 hours
pauseDuration = 1200UL;
intruder = false; // so posting to TS continues during pause
numIntruders = 0;
} else { // otherwise, use received value
intruder = false; // so posting to TS continues during pause
numIntruders = 0;
}
pauseDuration *= 60000UL; // convert minutes to milliseconds
server.send(200, "text/plain", "pausing");
} else { // not break or pause
server.send(200, "text/plain", "ESP32 eye .151");
}
}
void reBootMe() { // run with /reboot
// see e32hardReset in test_espB folder for basis of this
server.send(200, "text/plain", "reboot in 2");
delay(2000);
esp_task_wdt_init(1, true);
esp_task_wdt_add(NULL);
while (true);
}
void doTSpost() { // run with /postTS
server.send(200, "text/plain", "posting a 2 to TS");
writeThingSpeak(2, distCurrent, snowFactor, paused);
}
void showTScode() { // run with /showTS
char myCstr[15];
snprintf(myCstr, 15, "TScode=%d", lastTScode);
server.send(200, "text/plain", myCstr);
}
void handleNotFound() {
server.send(404, "text/plain", "404: Not found");
}
void smtpCallback(SMTP_Status status) {
Serial.println(status.info());
if (status.success())
{
Serial.println("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.printf("Message sent failled: %d\n", status.failedCount());
Serial.println("----------------\n");
struct tm dt;
for (size_t i = 0; i < smtp.sendingResult.size(); i++)
{
SMTP_Result result = smtp.sendingResult.getItem(i);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.printf("Date/Time: %d/%d/%d %d:%d:%d\n", dt.tm_year + 1900, dt.tm_mon + 1, dt.tm_mday, dt.tm_hour, dt.tm_min, dt.tm_sec);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}
void setupMail() {
smtp.debug(0); // 0 = none
smtp.callback(smtpCallback);
session.server.host_name = SMTP_HOST;
session.server.port = SMTP_PORT;
session.login.email = AUTHOR_EMAIL;
session.login.password = AUTHOR_PASSWORD;
session.login.user_domain = "mydomain.net";
message.sender.name = "ESP Mail";
message.sender.email = AUTHOR_EMAIL;
message.subject = "Test sending plain text Email";
message.addRecipient("Someone", "phoneNum@mms.cricketwireless.net");
message.text.content = "This is simple plain text message";
message.text.charSet = "us-ascii";
message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_normal;
message.response.notify = esp_mail_smtp_notify_success | esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay;
message.addHeader("Message-ID: <abcde.fghij@gmail.com>");
}
void sendMyMailNow() {
if (!smtp.connect(&session)) {
Serial.println("failed to connec to smtp sesh");
return;
} else if (!MailClient.sendMail(&smtp, &message)) { /* Start sending Email and close the session */
//Serial.println("Error sending Email, " + smtp.errorReason());
}
}
David Evanshttps://se.mathworks.com/matlabcentral/profile/authors/11799851tag:se.mathworks.com,2005:Question/7610812021-03-03T02:11:24Z2021-03-03T02:16:15ZOrder List of Neighbors In Counter Clockwise FashionHello,
I am trying to generate the natural neighbors of all points in my data set here I have what I am currently doing for one point.
for i=1:3
for j=1:nt
if t(j,i)==5
nn(j,:)=t(j,:);
end
end
end
nn = nn(any(nn,2),:);
nn = unique(nn);
nn = nn(find(nn~=5));
Where t is the delaunay triangulation which is essentially acting as a connectivity list.
This yields the natural neighbors of point number 5 in the data set which I just picked 5 arbitrarily. What I would like is for it to order the coordinates in a counter clockwise manner going around point 5. Like this image:
From there I can compute this same thing for all data sites. Is there also a better way to compute this without the nested for loops I am running to search the Delaunay triangulation?
Thanksshan siddiquihttps://se.mathworks.com/matlabcentral/profile/authors/12539810tag:se.mathworks.com,2005:Question/967932009-06-27T01:11:00Z2021-03-03T02:14:11ZWhy does a distorted figure result from copying to a Windows Metafile using a widescreen laptop and MATLAB 7.0.4 (R14SP2)?I am using MATLAB 7.0.4 (R14SP2) with a widescreen laptop. I would like to copy-and-paste figures into another application, but the figure appears distorted when pasted and displayed in the other application.
MathWorks Support Teamhttps://se.mathworks.com/matlabcentral/profile/authors/4622813tag:se.mathworks.com,2005:Question/7609762021-03-02T23:10:11Z2021-03-03T02:10:49Zdraw lines using the extractes angles and rhos from radon transformHello,
I am trying to draw the lines using the infromation extracted by radon transform. an example of what I am trying to do is demonstrated here. I am trying to draw lines with different rhos and thetas I get from radon transform just like the example. The coordinates I am getting is in polar format and the origin is concidered to be the center of the image(radon transform does it based on the center). How can I do that?
Thanks for your helpKasra Sadatsharifihttps://se.mathworks.com/matlabcentral/profile/authors/18460922tag:se.mathworks.com,2005:Question/7600512021-03-02T05:22:30Z2021-03-03T02:09:00ZHow can I get slope from DEM data? Hi, I'm undergraduate student from Yonsei University, Seoul. I have a question about MATLAB.
I have a DEM data like this picture.
Each row and column indicates the legth of data set(1952X2101), and each value means elevation.
I want to calculate the slope of radom radial degree.
If I put random radial degree like 45 degree(0-90 degree), MATLAB shows slope like 0.08 (in ratio)
How can I make this one?
Thanks for reading. HyoJae Leehttps://se.mathworks.com/matlabcentral/profile/authors/21523258tag:se.mathworks.com,2005:Question/7433222021-02-12T07:13:06Z2021-03-03T02:07:03ZHow to calculate the automatically some distance in the image based on the colour ? Hello all, I am interested to calculate the automatically some distance in the image based on the colour. Is it possible to calculate the distance ? For example i want to calculate the Ha1 , Ha2 , Ha3 and Ha4 in the sample a , Hb1 , Hb2 , Hb3 and Hb4 in the sample b, Hc1 , Hc2 , Hc3 and Hc4 in the sample c, Hd1 , Hd2 , Hd3 and Hd4 in the sample d, He1 , He2 , He3 and He4 in the sample e
please find the general image and image to calculate the distance. I am not expert at MATLAB, but i am interested to learn this code. I will appreciate if any one tell me an code to perform this operation.
Thanks a tonKristen Chappelhttps://se.mathworks.com/matlabcentral/profile/authors/21509178tag:se.mathworks.com,2005:Question/7557942021-02-25T10:42:59Z2021-03-03T02:04:25Zis their any way to calculate automatically this parameter from the image ?Hi all,
I am looking for the calculate the the parameter mentioned in the image, Is that possible to calculate from the image ?
(I have attached the original image and other one attached to understand you that which value i need to calculate, (Black width, highlighted with the lime colour))Thank you.Anish Khanhttps://se.mathworks.com/matlabcentral/profile/authors/21629885tag:se.mathworks.com,2005:Question/5428312020-06-05T13:15:37Z2021-03-03T02:03:36ZDownloading HYCOM data using Matlab and OPeNDAPI am trying to download HYCOM (www.hycom.org) data using the OPeNDAP access method and MATLAB. The data url can be generated by selecting desired variables from this link. I need to download the data using scripts to automate the download of many years of data.
My MATLAB code looks like below, which you should be able to run as well without any modification:
% This script download the Global HYCOM reanalysis data for a given time step
for i=0:2863
timestep = 1; % This value need to be adjusted for duration of the record needed
j=i+timestep;
url = ['http://tds.hycom.org/thredds/dodsC/GLBv0.08/expt_53.X/data/1994?depth[0:1:39],lat[0:1:3250],lon[0:1:4499],time['...
num2str(i) ':1:' num2str(j) ...
'],tau[0:1:2864],water_u[0:1:0][0:1:0][0:1:0][0:1:0],water_u_bottom[0:1:0][0:1:0][0:1:0],water_v[0:1:0][0:1:0][0:1:0][0:1:0],water_v_bottom[0:1:0][0:1:0][0:1:0],water_temp[0:1:0][0:1:0][0:1:0][0:1:0],water_temp_bottom[0:1:0][0:1:0][0:1:0],salinity[0:1:0][0:1:0][0:1:0][0:1:0],salinity_bottom[0:1:0][0:1:0][0:1:0],surf_el[0:1:0][0:1:0][0:1:0]'];
info = ncinfo(url);
% Successfully read these variables
depth = ncread(url, 'depth');
lat = ncread(url, 'lat');
lon = ncread(url, 'lon');
time = ncread(url, 'time');
% Trouble reading below variables
water_u = ncread(url, 'water_u');
water_v = ncread(url, 'water_v');
water_u_bottom = ncread(url, 'water_u_bottom');
water_v_bottom = ncread(url, 'water_v_bottom');
surf_el = ncread(url, 'surf_el');
water_temp = ncread(url, 'water_temp');
end
The scripts reads the depth, lat, lon, time fine, but gives error in reading the water_u variable on wards. The error message is:
Error using netcdflib
The NetCDF library encountered an error during execution of 'getVarShort' function - 'Index exceeds dimension bound
(NC_EINVALCOORDS)'.
Error in netcdf.getVar (line 136)
data = netcdflib(funcstr,ncid,varid,varargin{:});
Error in internal.matlab.imagesci.nc/read (line 605)
data = netcdf.getVar(gid, varid);
Error in ncread (line 58)
vardata = ncObj.read(varName, varargin{:});
I am not sure what is wrong with my code, and couldn't find any answer searching online so far. Appreciate your help.Amitava Guhahttps://se.mathworks.com/matlabcentral/profile/authors/4648702tag:se.mathworks.com,2005:Question/7609462021-03-02T21:43:20Z2021-03-03T01:52:01ZWhat should I do if the brightness of backgroud is very close to foreground?Hi,
I have some images that I want to segment. However, The the brightness of backgroud is very close to foreground in my images.
Here is a example,
The red circled object is what I want. But after trying different methods, this is what I got
Is there any suggestions to get a better result? These segmented images are used to be mask for 3D segmentation by using ‘activecontour’. Other images have similar problem. And as you can imagine, The 3D structure is much larger than what I want.
Thanks!Dongyu Lianghttps://se.mathworks.com/matlabcentral/profile/authors/15487013tag:se.mathworks.com,2005:Question/7610762021-03-03T01:50:12Z2021-03-03T01:50:12ZPlotting Fourier Series With Step FunctionNeed help plotting this Fourier Sine series, but unsure how to do it with a step function. Also need help plotting the series graph for the 1st term. 1st 5 terms, and 1st 15 terms. Pls help
Will Jeterhttps://se.mathworks.com/matlabcentral/profile/authors/13962327tag:se.mathworks.com,2005:Question/892612013-10-05T17:39:44Z2021-03-03T01:47:05ZMeasuring the contact angle of droplet.I'm a beginner in image processing at Matlab.I would like to measure the static contact angle of a water droplet on surface. The purpose of this measurement is to determine whether a surface is hydrophobic or not. I've my input image. How can I start? Need some suggestions. Mollahttps://se.mathworks.com/matlabcentral/profile/authors/3686361tag:se.mathworks.com,2005:Question/1969852015-04-09T04:00:00Z2021-03-03T01:34:50ZHow do I change the display language of the MATLAB UI in Windows 7?My MATLAB desktop environment (in Windows 7) is displaying the UI elements in Chinese and I would like them in English. How do I display the UI in English?
MathWorks Support Teamhttps://se.mathworks.com/matlabcentral/profile/authors/4622813tag:se.mathworks.com,2005:Question/7604012021-03-02T13:17:08Z2021-03-03T01:28:02ZCumsum at different starting indices, append all previous value.Hello, say I have 2 continuous dataset for example:
A = [0 0 8 0] B = [1 0 0 0 0.5 1.5 0]
The algorithm iterates over each element i = i +1 to check if element >= 0.5. If True cumsum starts.
Condition: Cumsum ends when exceeds 2 within 3 indices. Append the values and index.
The final cumsum value is not important, it is a means to set the condition of appending relevant values.
So result for A will give:
result = [0, 0, 8], idx = 1, 2, 3 NOT result = [ 0 0 8 '0']
However, if the condition is not met. Ignore the cumsum and move on to the next value.
e.g.: B will start 1st cumsum at [1]: 1 + 0 + 0 = 1. Which fails to meet the condition. Hence ignored.
It continues iterating, until reaching 0.5 which then starts another cumsum.
So result for B will give:
val = [1 0 0 0 0.5 1.5] NOT [1 0 0] [1 0 0 0 0.5 1.5 '0']
How can I approach this? Many thanks.Jonathan Cheonghttps://se.mathworks.com/matlabcentral/profile/authors/15392330tag:se.mathworks.com,2005:Question/7610612021-03-03T01:14:32Z2021-03-03T01:14:32ZV2G phasor model to discrete modelHello community, I need help. How could I change the car model (V2G) that is in phasor mode to discrete mode. I have already tried but there are several errors related to the values of the current sources and the identification of the input variables.
Contact: bryanbsc@hotmail.comBryan Rodríguezhttps://se.mathworks.com/matlabcentral/profile/authors/15525696tag:se.mathworks.com,2005:Question/7610562021-03-03T01:10:37Z2021-03-03T01:12:06Z3d plot based on for loopI'm tying to create a 3D potential model for the code within the for loop. I think my problem is I'm not calling the V = line (and i, j, k lines) as a function, but I'm also unsure how to edit my for loop to reflect a function. I'm trying to use fsurf(f) to generate a 3D model. I am aware that at its current set up the for loop isn't doing anything, however it will be modified later to fit 8 different parameters, I'm using it as a summation (sigma).
This is for a class project, so I don't want the answer, but I do want to know where my problem(s) is(are) and what I should do to fix it(them). Thank you.
clear;
syms x y
V = [];
l = 0;
for m = 0:0
n = 2 .* m + 1;
i = 16 / ( (pi .^ 2) .* (n .^ 2));
j = (sin (n .* pi .* x) .* cosh( sqrt(2 .* n .^ 2) .* pi .* y)) / ( cosh ( sqrt (2 .* n .^ 2) .* pi));
k = sin (n .* pi / 2);
V = l + ( i .* j .* k) ;
l = V ;
end
V = V
f = @(x y)V
fsurf(f)Emmahttps://se.mathworks.com/matlabcentral/profile/authors/12678563tag:se.mathworks.com,2005:Question/7610512021-03-03T01:06:36Z2021-03-03T01:06:36ZNewton's MethodI have the following code for a recursive function for Newton method.
function [R] = myNewton(f,df,x0,tol)
if abs(f(x0)) < tol
R = x0;
else
[R] = myNewton(f,df,x0-(f(x0)/df(x0)),tol);
end
end
When I call this function I will need df, but I don't know how to make MATLAB take f and compute df. Tony Rankinhttps://se.mathworks.com/matlabcentral/profile/authors/14767101tag:se.mathworks.com,2005:Question/7610412021-03-03T00:50:17Z2021-03-03T01:03:25ZHow can I create a matlab matrix below? Hi, I've been wanting to construct a matlab matrix that is n by n. and looks like this. I've beeen trying to use diag but the function diag doesn't provide this. so m a bit confused. Please help!
kimjandihttps://se.mathworks.com/matlabcentral/profile/authors/16369347tag:se.mathworks.com,2005:Question/7610212021-03-03T00:34:58Z2021-03-03T01:00:00ZHow can i find unknown variable in matrixF=K*D
How can i find D1 D2 in term AE?fatih ayçahttps://se.mathworks.com/matlabcentral/profile/authors/21643063tag:se.mathworks.com,2005:Question/6409702020-11-08T21:15:17Z2021-03-03T00:52:04ZMatlab disables monitor sleeping under UbuntuIt seems once Matlab starts, the Ubuntu monitor won't fall into sleep, but stay on all the time on some Matlab versions.
I have searched solutions for the issue, but all I found are how to disble screen saver under Linux.
Here are my limited test:
On an Ubuntu 16.04 machine, Matlab R2017a has no problem. Even if Matlab is running, the monitor will get into sleep mode based on the setting.
On the same Ubuntu, Matlab R2019b gives the problem. Once Matlab is running, the monitor will stay on.
On another Ubuntu 18.04, both Matlab R2019b and R2020a give the same problem: monitor stays on once Matlab is running.
In all tested cases, after Matlab exists, the monitor will get into sleep mode without problem.
Any idea or workaround? Thanks.Xiangrui Lihttps://se.mathworks.com/matlabcentral/profile/authors/2685526tag:se.mathworks.com,2005:Question/4079222018-06-28T15:57:36Z2021-03-03T00:51:41ZDeleted table rows stuck in memory? Cannot fit a linear model.I have a data table with both continuous and categorical values. I want to run a linear model for this table using 'fitlm'. I have a loop where I pick a different subset of rows and fit a model for it.
However, it appears that I cannot do slicing for categorical variables. Fitlm sees all possible categories of the full table and complains "Warning: Regression design matrix is rank deficient to within machine precision.". The non-existing categories also appear in the model. Even creating a temporary table from numerical matrix does not help!
Here is an example. I don't understand why one categorical factor (condition 3) won't go away.
% data with 3 categories
data = [...
1.9,1;
5.7,2;
0.7,1;
2.2,2;
0,1;
1.9,2;
-0.2,1;
1.6,2;
-0.7,1;
2.3,2;
1,3];
% create table
data_table = array2table(data,'VariableNames',{'Y','Condition'});
% make condition as categorical
data_table.Condition=categorical(data_table.Condition);
% fit linear model (basically a t-test)
model1 = fitlm(data_table,'Y ~ 1 + Condition');
% this works, but condition 3 is basically useless with only 1 sample
% Lets remove the final row and condition 3
data_table = data_table(1:end-1,:);
% repeat with sliced table (only 2 categories remains)
model2 = fitlm(data_table,'Y ~ 1 + Condition');
% We get a warning. Condition 3 is still there with no data.
% Create a new table from a numerical array
mat = table2cell(data_table);
new_data_table = cell2table(mat,'VariableNames',{'Y','Condition'});
new_data_table.Condition=categorical(new_data_table.Condition);
% no category 3 in the new table
model3 = fitlm(new_data_table,'Y ~ 1 + Condition');
% still the same warning even if there never was condition 3 in this table
% ok, lets clear old tables and start from the cell matrix
clear data_table new_data_table data;
new_new_data_table = cell2table(mat,'VariableNames',{'Y','Condition'});
new_new_data_table.Condition=categorical(new_new_data_table.Condition);
% again, no category 3 in the new table
model4 = fitlm(new_new_data_table,'Y ~ 1 + Condition');
% still the same warning, condition 3 remains
ADDITION:
In the latest version of Matlab I could probably use "removecats" to delete non-existing categories. However, this function is not available in r2017b.
Janne Kauttonenhttps://se.mathworks.com/matlabcentral/profile/authors/2880105tag:se.mathworks.com,2005:Question/7609512021-03-02T21:43:30Z2021-03-03T00:46:36ZUndefined function 'C' for input arguments of type 'double'.hello!
i am running into a problem with my script with this line:
whole_ts = {1:2150, 1:1928, 1:2426};
I've tried:
whole_ts = [{1:2150, 1:1928, 1:2426}];
whole_ts = (1:2150, 1:1928, 1:2426);
whole_ts = [C{1:2150, 1:1928, 1:2426}];
whole_ts = timeseries([1:2150], [1:1928], [1:2426])
this one seems the most promising:
whole_ts = [C{1:2150, 1:1928, 1:2426}];
where i am getting this error:
Undefined function 'C' for input arguments of type 'double'.
I am trying to load it into a cell like I did with the 'trs' variable which is 1x3 but 'whole_ts' has is [1:2150, 1:1928, 1:2426].
%% loading TACS
subj = {'subj01' 'subj02' 'subj03'}
trs = [2.8, 2.2, 2.2];
whole_ts = [C{1:2150, 1:1928, 1:2426}];
for k = 1:3
ts{k} = load(fullfile(D,subj{k},'ts','thalamus_ts.txt'));
whole_ts = 1:length(ts{k})
t_mr_1 = (1:length(whole_ts))*(trs(k)/60)
subplot(3,1,k), hold on
plot(t_mr_1, ts{k})
end
Any help would be much appreciated!
nineshttps://se.mathworks.com/matlabcentral/profile/authors/15883041tag:se.mathworks.com,2005:Question/7610162021-03-03T00:34:39Z2021-03-03T00:34:39ZHow can I evaluate characteristic functions in MatLab?I want to numerically evaluate characteristic functions (CF) of PDFs (definition: https://en.wikipedia.org/wiki/Characteristic_function_(probability_theory) )
For example, the CF of the Normal distribution is
where is the CF variable, is the distribution mean, is its variance and is the imaginary unit. If I numerically construct a normal distribution as below, how could I numerically estimate its charactertic function?
avg = 1; % average
s = 1; % standard deviation
dx = 0.01;
x = (avg - 5*s):dx:(avg+5*s);
gaussian = 1/sqrt(2*pi*s^2) * exp ( - 0.5 *( x - avg ).^2 / s^2 ); Martim Zuritahttps://se.mathworks.com/matlabcentral/profile/authors/10397005tag:se.mathworks.com,2005:Question/7599312021-03-02T01:46:16Z2021-03-03T00:31:57ZFor cell coverage coding
I would like to caclulate of cell coverage in this picture.
Finally, I decide that if it can be caclulate with slope each axis, it's gonna be.
For example, in this red box, from left, the interval 41 to 59 is not cell part. it looks like blurred part.
So, first high slope is not in cell, but the next high slope is look like cell part.
Therefore, in that area, it can be recognized cell part between next high slope( the value is 80 or 109) after first high slope and back side value which 78 or 109 that the right side value in red box.
Of course, it's should be caculated not only X axis, but Y axix.
I want to know this coding.
저는 세포의 커버리지를 알고 싶습니다. 일반적으로 쓰이는 방법들은 실제 세포와 빛의 번짐의 구분이 명확하지 않은 것 같습니다. 결과적으로는 픽셀값 사이의 증가율과 감소율로 세포의 경계를 구분할 수 있다고 생각됩니다.
예를 들어 사진에 있는 빨간 박스안에서 왼쪽부터 숫자가 점점 증가하는데 50미만의 픽셀값에서는 의미가 없습니다. 하지만 50이상의 값에서 부터의 기울기는 의미가 있습니다.
왼쪽 41값에서 59값의 증가율은 세포의 실제 영역과 관계가 없어보이지만 그 다음 값인 59값에서 80값의 증가율은 세포의 실제영역과 관계가 있어보입니다. 다시 말해 80값의 픽셀부터는 세포의 영역으로 표시된다고 판단되고 더 오른쪽에 있는 값들 중 109나 78값부터는 세포의 영역이 끝난다고 보여집니다.
이러한 방법으로 X축과 Y축에서 픽셀값의 증가와 감소에 따른 기울기로 binary 할 수 있다면 세포의 실제영역을 계산하여 커버리지를 알아낼 수 있을 것 같습니다.
이에 대한 코딩을 알고 싶습니다.
P.S : 사진을 전체적으로 볼 때 사진의 중앙에 더 많은 빛이 들어오므로 사진의 가장자리는 셀의 영역이라해도 값이 낮아 특정값을 기준으로 substracting 하는 것은 문제가 있습니다.동희 정https://se.mathworks.com/matlabcentral/profile/authors/21692734tag:se.mathworks.com,2005:Question/7607662021-03-02T18:39:12Z2021-03-03T00:18:04ZWhy does subclassing a numeric type break its use as a property of a custom class?I’m seeing some odd behavior while trying to use a subclassed numeric type in a custom class I’m creating. Within the custom class, if I specify a property as a vector of type double, I can specify a default value as a scalar and everything works as expected (it fills the vector with copies of the scalar value if I don’t provide an input). But as soon as I change the type to a subclass of double, such as the ExtendDouble example given in the documentation here, I can no longer use a scalar as the default value, even though the error message itself says I should be able to:
>> testClass([1;2;3])
Error setting default value of property 'param1' of class 'testClass':
Size of default value must match specified dimensions 3×1 or be scalar.
So I have two questions:
1. Why does my code work for double but not ExtendDouble?
2. Why is it even trying to use the default value at all, when I’ve explicitly provided the value as an input argument to the constructor?
My custom class code is as follows:
classdef testClass
properties
param1(3,1) ExtendDouble = 0
end
methods
function self = testClass(param1)
if nargin > 0
self.param1 = param1;
end
end
end
endDavid Sempsrotthttps://se.mathworks.com/matlabcentral/profile/authors/18417342tag:se.mathworks.com,2005:Question/7544892021-02-24T05:02:59Z2021-03-03T00:14:22ZEnforce action space constraints within the environmentHi,
My agent is training!!! But it's pretty much 0 reward every episode right now. I think it might be due to this:
contActor does not enforce constraints set by the action specification, therefore, when using this actor, you must enforce action space constraints within the environment.
How can I do this?
Also, is there a way to view the logged signals as the agent is training?
Thanks!
John Doehttps://se.mathworks.com/matlabcentral/profile/authors/19188654tag:se.mathworks.com,2005:Question/7449922021-02-14T11:44:49Z2021-03-03T00:14:06ZOptimization of an implicit function using fminconI am trying to carry out multi-objective constrained optimization using fmincon in MATLAB. However, one of my objective function can not be brought in an explicit form depending on variables. For example, I have an equation like:
x^a + x^b = y
and I want to minimize x given a range of values for a, b and y respectively.
How can I do that?
Harshit Agrawalhttps://se.mathworks.com/matlabcentral/profile/authors/12174221tag:se.mathworks.com,2005:Question/7609862021-03-02T23:14:00Z2021-03-03T00:06:21ZI need help figuring the code out. Find the area enclosed by y = e^x , y = x, x = 0, and x = 2 please help me code this problem pleaseKelsey Duggerhttps://se.mathworks.com/matlabcentral/profile/authors/19313692tag:se.mathworks.com,2005:Question/7485622021-02-17T23:36:59Z2021-03-03T00:04:29ZCant ignore errors anymoreI used to have an options with right mouse click to ignore any errors in the editor, but it no longer apears. What happened to it? This is worse than irritating as it makes it difficult to see if the file contains errors. For example, when appending a table with a cell of strings the editor gives an error saying that I should be using square braces. I now have to continuously go through every error to see if it is something that should be ignored or not.Matthew Parryhttps://se.mathworks.com/matlabcentral/profile/authors/8865413tag:se.mathworks.com,2005:Question/5093242020-03-06T01:57:07Z2021-03-02T23:48:59ZTable: Remove all columns that only have zerosI am new to Matlab, but I could not find this after substantial searching. I am using R2018B.
I am opening an excel sheet with:
data = readtable(file)
I would like to delete all columns that only have zeros in them. I am using a table so I do not lose my headers or the correct alignment of the headers.
Can someone please help me? Thanks in advance!Kevin Kaufmannhttps://se.mathworks.com/matlabcentral/profile/authors/12412010