https://se.mathworks.com/matlabcentral/answers/questionsMATLAB Answers ā New Questions2020-02-19T01:35:36Ztag:se.mathworks.com,2005:Question/5061342020-02-18T09:49:41Z2020-02-19T01:35:36ZHow do i find the intersection between two torus ?I have 2 torus in three-dimensional space, and i need to find the intersection between them
R=9; % outer radius of torus
r=3; % inner tube radius
th=linspace(0,2*pi,36); % e.g. 36 partitions along perimeter of the tube
phi=linspace(0,2*pi,18); % e.g. 18 partitions along azimuth of torus
% we convert our vectors phi and th to [n x n] matrices with meshgrid command:
[Phi,Th]=meshgrid(phi,th);
% now we generate n x n matrices for x,y,z according to eqn of torus
x1= (R+r.*cos(Th)).*cos(Phi) +9;
y1= r.*sin(Th) ;
z1= (R+r.*cos(Th)).*sin(Phi);
daspect([1 1 1]) % preserves the shape of torus
colormap('jet') % change color appearance
hold on
x2= ((R+r.*cos(Th)).*cos(Phi))*cos(2*pi/3) - (r.*sin(Th))*sin(2*pi/3) - 4.5;
y2= ((R+r.*cos(Th)).*cos(Phi))*sin(2*pi/3) + (r.*sin(Th))*cos(2*pi/3) + 9*sin(pi/3);
z2= (R+r.*cos(Th)).*sin(Phi);
surf(x1,y1,z1); % plot surface
surf(x2,y2,z2);
daspect([1 1 1]) % preserves the shape of torus
colormap('jet') % change color appearance
title('Torus')
xlabel('X');ylabel('Y');zlabel('Z');
Duc Lehttps://se.mathworks.com/matlabcentral/profile/authors/12648835-duc-letag:se.mathworks.com,2005:Question/5058902020-02-17T07:59:07Z2020-02-19T01:33:46ZHow to write a matlab code to automate the bulk write procedure on ThingspeakHow to write a matlab code to automate the bulk write procedure on ThingspeakDivyansh Deshmukhhttps://se.mathworks.com/matlabcentral/profile/authors/17149012-divyansh-deshmukhtag:se.mathworks.com,2005:Question/5034242020-02-03T17:26:12Z2020-02-19T01:31:46Zhow can i plot 3 parameters in (x y) axis as shown in figHi,
how can I plot a variable that change due to 2 parameters as shown in Fig SALEH ALHUMAIDhttps://se.mathworks.com/matlabcentral/profile/authors/14902225-saleh-alhumaidtag:se.mathworks.com,2005:Question/5055992020-02-15T07:21:45Z2020-02-19T01:31:31Zneed help with Talk back, commands and fieldsHi,
I try to control some relays thr TalkBack app.
Using ESP 8266.
Everything connecting to Internet.
I got stuck on how to activate relay. I used Key, used ID. I cant find how to send command thru TalkBack
I dont know what Command ID for, and how to send command string.
Need some help please
Also here is my code and some screenshots:
#include "ThingSpeak.h"
#include "ESP8266WiFi.h"
const char ssid[] = "XXX"; // your network SSID (name)
const char pass[] = "YYY"; // your network password
#define RELAY1 12
#define RELAY2 13
#define RELAY3 14
#define RELAY4 16
WiFiClient client;
//---------Channel Details---------//
unsigned long counterChannelNumber = 123; // Channel ID
const char * myCounterReadAPIKey = "ZZZ"; // Read API Key
const int FieldNumber1 = 1; // The field you wish to read
const int FieldNumber2 = 2; // The field you wish to read
const int FieldNumber3 = 3; // The field you wish to read
const int FieldNumber4 = 4; // The field you wish to read
//-------------------------------//
void setup()
{
Serial.begin(115200);
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
}
void loop()
{
//----------------- Network -----------------//
if (WiFi.status() != WL_CONNECTED)
{
Serial.print("Connecting to ");
Serial.print(ssid);
Serial.println(" ....");
while (WiFi.status() != WL_CONNECTED)
{
WiFi.begin(ssid, pass);
delay(5000);
}
Serial.println("Connected to Wi-Fi Succesfully.");
}
//--------- End of Network connection--------//
//---------------- Channel 1 ----------------//
Serial.print("Reading field 1 ");
long R_Status = ThingSpeak.readLongField(counterChannelNumber, FieldNumber1, myCounterReadAPIKey);
int statusCode = ThingSpeak.getLastReadStatus();
if (statusCode == 200)
{
Serial.print("Read field 1 Successful ");
// Serial.println(temp);
}
else
{
Serial.println("Unable to read channel / No internet connection");
}
Serial.println(R_Status);
if(R_Status==1)
{
digitalWrite(RELAY1, HIGH); //Relay 1 ON
Serial.println("Relay 1 ON");
}
if(R_Status==2)
{
digitalWrite(RELAY1, LOW); //Relay 1 OFF
Serial.println("Relay 1 OFF");
}
Serial.print("Reading field 2 ");
delay(5000);
long R_Status2 = ThingSpeak.readLongField(counterChannelNumber, FieldNumber2, myCounterReadAPIKey);
int statusCode2 = ThingSpeak.getLastReadStatus();
if (statusCode2 == 200)
{
Serial.print("Read field 2 Successful ");
// Serial.println(temp);
}
else
{
Serial.println("Unable to read channel / No internet connection");
}
Serial.println(R_Status2);
if(R_Status2==1)
{
digitalWrite(RELAY2, HIGH); //Relay 2 ON
Serial.println("Relay 1 ON");
}
if(R_Status2==2)
{
digitalWrite(RELAY2, LOW); //Relay 2 OFF
Serial.println("Relay 1 OFF");
}
Serial.print("Reading field 3 ");
delay(5000);
long R_Status3 = ThingSpeak.readLongField(counterChannelNumber, FieldNumber3, myCounterReadAPIKey);
int statusCode3 = ThingSpeak.getLastReadStatus();
if (statusCode3 == 200)
{
Serial.print("Read field 3 Successful ");
// Serial.println(temp);
}
else
{
Serial.println("Unable to read channel / No internet connection");
}
Serial.println(R_Status3);
if(R_Status3==1)
{
digitalWrite(RELAY3, HIGH); //Relay 3 ON
Serial.println("Relay 3 ON");
}
if(R_Status3==2)
{
digitalWrite(RELAY3, LOW); //Relay 3 OFF
Serial.println("Relay 3 OFF");
}
Serial.print("Reading field 4 ");
delay(5000);
long R_Status4 = ThingSpeak.readLongField(counterChannelNumber, FieldNumber4, myCounterReadAPIKey);
int statusCode4 = ThingSpeak.getLastReadStatus();
if (statusCode4 == 200)
{
Serial.print("Read field 4 Successful ");
// Serial.println(temp);
}
else
{
Serial.println("Unable to read channel / No internet connection");
}
Serial.println(R_Status4);
if(R_Status4==1)
{
digitalWrite(RELAY4, HIGH); //Relay 4 ON
Serial.println("Relay 4 ON");
}
if(R_Status4==2)
{
digitalWrite(RELAY4, LOW); //Relay 4 OFF
Serial.println("Relay 4 OFF");
}
delay(10000); // ThingSpeak will only accept updates every 10 seconds.
}
Pavel Plotinnovhttps://se.mathworks.com/matlabcentral/profile/authors/17228698-pavel-plotinnovtag:se.mathworks.com,2005:Question/5059112020-02-17T10:23:27Z2020-02-19T01:30:11Zcsv upload fails "...contains invalid location fields"Hey, (sorry about my english)
since yesterday I got , during CSV Upload, the Error message : "The file was not uploaded because it contains invalid location fields"
My investigation, what is wrong with the csv-file, was not helpfull, I found nothing (for me) obvious wrong. The upload procedure I have done a lot of times in the past, w/o any issue!!! but now ?????
(I double checked the file with Excel, notepad++, textpad... deleted rows in the file, added manualy some field values in an row,.... reduced a dummy file to only 10 rows....
==> some times it worked, sometimes not.)
What is the KEY Reason for this error massage? a certain coding? after checking since hours, trying different minor/major changes, I have no glue what is wrong.
I need a simple hint in what direction or on what "Point (?)" I have to check?!?!
....
The File I wants to upload is from TS downloaded -> deleted some (faulty) rows -> upload again.
The Upload procedure I make 1000 of times in the past.... but since yesterday, I was not lucky. :-(((
cheers & thanks in advance
JoachimYam Schusterhttps://se.mathworks.com/matlabcentral/profile/authors/15232685-yam-schustertag:se.mathworks.com,2005:Question/5062442020-02-18T19:07:35Z2020-02-19T01:22:42Zreturn any angle to (0 to 2pi) rangeI have a cetain angle let us say x
and I want matlab to change x to become within 0 and 2pi range
example: if x=3pi
then the new value of x have to be piOsama Al-Kurdihttps://se.mathworks.com/matlabcentral/profile/authors/17431831-osama-al-kurditag:se.mathworks.com,2005:Question/5062162020-02-18T16:49:17Z2020-02-19T01:18:40ZPrecision quandaries: why can I print 64 digits?I've been testing a Modified Gram-Schmidt algorithm that is part of a larger pipeline:
function [Q, R] = mgs(X)
% [Q, R] = MGS(X) performs Modified Gram-Schmidt on the m x s matrix X.
%%
% Pre-allocate memory for Q and R
[m, s] = size(X);
R = zeros(s,s);
Q = zeros(m,s);
% Modified Gram-Schmidt
R(1,1) = norm(X(:,1));
Q(:,1) = X(:,1)/R(1,1);
for k = 1:s-1
w = X(:,k+1);
for j = 1:k
R(j,k+1) = Q(:,j)'*w;
w = w - Q(:,j)*R(j,k+1);
end
R(k+1,k+1) = norm(w);
Q(:,k+1) = w/R(k+1,k+1);
end
end
Farther down the software pipeline, I measure loss of orthogonality and backward error. My colleague ran our software on her machine and found that for several key examples I have nearly full orthogonality and she has none. I am 100% certain we are using the same X and software (we checked; everything is pushed and pulled through Git).
We found something surprising with the following script that may explain the issue:
% mgs test
X = magic(10); X = X(:,1:2);
[Q, R] = mgs(X);
fprintf('||I - Q''*Q|| = %0.64e\n', norm(eye(2) - Q'*Q)); % loss of orthogonality
fprintf('||Q*R - X|| = %0.64e\n', norm(Q*R - X)); % backward error
% Results on my machine:
% mgs:
% ||I - Q'*Q|| = 4.1017407521273322775592436112613973088682572487422006712876054735e-16
% ||Q*R - X|| = 1.7763568394002504646778106689453125000000000000000000000000000000e-15
The same script on her machine prints trailing 0's after the 16th digit for both quantities.
I had assumed that Matlab computed in double precision regardless of the machine, but it would seem that Matlab is somehow utilizing higher precision on my machine than on my colleague's. Or is there another explanation for why I can print 64 digits of precision?
My specs: Matlab 2019a, Windows 10 64-bit, Intel Core i7-8850U CPU @ 1.80GHz, 16GB RAM, Thinkpad X1 Carbon Gen 6
Colleague's: Matlab 2017a, Windows 7 (don't know the rest but her Thinkpad is about 6 years older than mine, so likely lacking some features that mine has)
Kathryn Lundhttps://se.mathworks.com/matlabcentral/profile/authors/13190313-kathryn-lundtag:se.mathworks.com,2005:Question/5062962020-02-19T01:15:14Z2020-02-19T01:15:14ZQuiver3 plot with pcnormals depending on magnitude / directionI had an 3D point cloud that successfully plotted by Quiver3 with its normals. But I am wondering how can I index and plot it depending on magnitude / direction ?
The point cloud is somehow dense that Quiver - magnitude depending color in 2D and 3D cannot cater for my large datasets. Peter LAUhttps://se.mathworks.com/matlabcentral/profile/authors/17339064-peter-lautag:se.mathworks.com,2005:Question/4786682019-09-03T09:04:18Z2020-02-19T01:10:13ZHow to clear (not close) all the opened figures?I would like to ask what is the easiest way to clear all the figures (not closing them) already opened.
The "clf" command is useful, but it clears only the current figure.
Is there a command or some easy instruction to clear all figures, such as "close all" used for closing them?Giovanni Franzinihttps://se.mathworks.com/matlabcentral/profile/authors/10553623-giovanni-franzinitag:se.mathworks.com,2005:Question/5062882020-02-18T23:02:42Z2020-02-19T01:01:44ZHow to delete a cell in gui Hi, I want to delete a line from a plot in GUI. To do that, I have created the following code:
line1=num2str(get(handles.plotHandles,'XData'));
delete(line1)
where line1 is composed of 2x1 cells = [ 1x2 double]
[1x2 double]
it seems something is wrong here but I cannot find the solution. I am getting the following error:
Any suggestion to fix this error?
Undefined function 'abs' for input arguments of type 'cell'.
Error in num2str (line 66)
xmax = double(max(abs(widthCopy(:))));
Error in Loading_Well_logs>pushbutton8_Callback (line 1931)
line1=num2str(get(handles.plotHandles,'XData'));
Error in gui_mainfcn (line 95)
feval(varargin{:});
Error in Loading_Well_logs (line 42)
gui_mainfcn(gui_State, varargin{:});
Error in @(hObject,eventdata)Loading_Well_logs('pushbutton8_Callback',hObject,eventdata,guidata(hObject))
Error while evaluating UIControl Callbackleydy Garciahttps://se.mathworks.com/matlabcentral/profile/authors/11656708-leydy-garciatag:se.mathworks.com,2005:Question/5056242020-02-15T12:27:06Z2020-02-19T01:00:28ZI want to calculate m, b using the polyfit function over and over and over again.x = randn(1, 100)
y= randn(1, 100)
P= polyfit (x,y,1)
m = P(1)
b = P(2)
In this way, m and b values, which are put into the primary function, will be displayed in the interval between 1 and 100.
But I'm one to five, five to ten, ... I would like to calculate m, b, and draw a scatterplot from 95 to 100.jungmin parkhttps://se.mathworks.com/matlabcentral/profile/authors/17371525-jungmin-parktag:se.mathworks.com,2005:Question/5062732020-02-18T22:04:05Z2020-02-19T00:55:48ZMax of vector in higher dimensional array subject to constraintsHello all,
I currently have code that's working but inefficient due to nested for loops, and I would like to vectorize it as possible. My data set is a higher dimensional array (a,b,.....z), and I'd like to find the maximum of each vector of z subject to a constraint based on the values of the other vectors.
For example, take a 3 dimensional array (a,b,c). I will have calculated a matrix (a x b-sized) of a constraint. I'd like to find a (a x b-sized) matrix that gives the maximum of each c vector that is measured only on the domain of (constraint:end). Let me know if there is a way to do this without for loops.
(edited for clarity)James Leehttps://se.mathworks.com/matlabcentral/profile/authors/17574263-james-leetag:se.mathworks.com,2005:Question/5062402020-02-18T18:52:07Z2020-02-19T00:53:41ZSpectral analysis resolution outputDear all, How are u?
I'm using spectral analysis with hourly wind vectors, and the result shows peaks of energy like 12.4, 20.4, 14.7 hours, but i don't understand why if I'm using hourly wind data, the result show me hours with decimals (minutes, It should show only peak energy in exact hours?). I know that this maybe a stupid question, but for that result I should be using something like 10 minutes hour time series?
Best regardsSherlock Holmeshttps://se.mathworks.com/matlabcentral/profile/authors/4429691-sherlock-holmestag:se.mathworks.com,2005:Question/5057222020-02-16T00:50:48Z2020-02-19T00:53:22ZWhy Matlab does not plot "for loop" generated vector?I am quite a beginner and after hours of googling I just could not figure out why Matlab does not plot what needed. I can see only a blank.
My script is:
c = 7;
n=12;
for i = 0:1:n
u=i;
p_u = (2.3/c)*((u/c)^1.3)*exp(-(u/c)^2.3);
hours =8760*p_u*(1-0.09);
hold on;
plot(u, hours)
end
Thank you in advance!Annehttps://se.mathworks.com/matlabcentral/profile/authors/9788156-annetag:se.mathworks.com,2005:Question/5062912020-02-18T23:31:34Z2020-02-19T00:50:38Zdiscrte to softmax : Attempt to grow array along ambiguous dimensionHello
Im trying to run below function but constantly getting error
Attempt to grow array along ambiguous dimension.
Error in discrete2softmax (line 5)
s_m([1:sNum] + (inp'-1)*sNum) = 1;%problem
I know its caused becouse target is larger then array but please help how i should change my code to make it work
function s_m = discrete2softmax(inp,nmax)
% Convert discrete data into softmax
sNum = size(inp,1);
s_m = zeros(sNum,nmax);
s_m([1:sNum] + (inp'-1)*sNum) = 1;%problem
end
Tomasz Kaczmarskihttps://se.mathworks.com/matlabcentral/profile/authors/17173063-tomasz-kaczmarskitag:se.mathworks.com,2005:Question/5062952020-02-19T00:49:17Z2020-02-19T00:49:17ZImplement the Urban Okumura ā Hata model in MatlabI need some help implementing the Urban Okumura-Hata Model into Matlab script. I don't really know how to get started and am looking for something to help get me started, so any help would be appreciated.
Implement the Urban Okumura ā Hata model in Matlab script. Plot the distance Vs attenuation loss graph with following parameters. Distance Tx-Rx: 1 to 10 Km with step of 1Km. Use three freuquencies 150MHz, 1000MHz, and 1500MHz on the same plot. Clearly show horizontal axis as distance and vertical axis of the plot as loss in dB. Use appropriate colors, labels, and scale to show your matlab plot.
Nathan Jaquahttps://se.mathworks.com/matlabcentral/profile/authors/16087556-nathan-jaquatag:se.mathworks.com,2005:Question/5048112020-02-11T07:51:50Z2020-02-19T00:45:26ZHow do I find the the zero state diretion and the zero input direction of a transfer matrix in Matlab?I want to compute using matlab the Rosenbrock System Matrix, and in particular I am trying to do a an analysis similar to the one at the end of http://people.duke.edu/~hpgavin/ce263/zeros.pdf . So, starting from a transfer matrix I would like to show that if there is a zero at a certain position, there is a zero blocking property.
To do so, as written in the link, I have to find the zeros state direction and the zero input direction, and I am having troubles doing do.
I am considering a different system from the one in the link, so I am trying to do a similar analysis applied to another system, and I am doing this:
s = tf('s');
P = 1/(s+5);
C = 6/s;
S = 1/(1+P*C);
T = P*C/(1+P*C);
G_2 = [T S; S -S]; %transfer matrix
Now, I have that my transfer matrix is :
G_2
and for it I would like to do the analysis to find the zero state diretion and the zero input direction, but I am having troubles doing so.
Can somebody please help me? Thanks in advance.Flavio Clariziahttps://se.mathworks.com/matlabcentral/profile/authors/14897372-flavio-clariziatag:se.mathworks.com,2005:Question/5060942020-02-18T05:41:44Z2020-02-19T00:39:09ZCan't import csv file into thingspeak.I cant import csv files into thingspeak. Is there a bug on the thingspeak side?Jimi Rex Pacetehttps://se.mathworks.com/matlabcentral/profile/authors/17056015-jimi-rex-pacetetag:se.mathworks.com,2005:Question/5062932020-02-19T00:36:42Z2020-02-19T00:38:05Zerror : Unable to use a value of type ClassificationNaiveBayes as an index.I trained a Naive Bayes model using:
nb = fitcnb(x, t, 'Distribution','kernel');
but when I try to classify new data :
i = predict(nb,values);
I got this error : Unable to use a value of type ClassificationNaiveBayes as an index.
what's wrong? Can anyone help me please?
PS: I use Matlab 2019bOUJAOURA MUSTAPHAhttps://se.mathworks.com/matlabcentral/profile/authors/3917470-oujaoura-mustaphatag:se.mathworks.com,2005:Question/5062942020-02-19T00:37:07Z2020-02-19T00:37:07ZFinding Rest of RowHello! Matlab newbie here. So I have a bunch of data in rows/columns. If I have a variable assigned to something in a specific row in column 1, how do I find the values in the rest of the row in the rest of the columns (there's like five total)? I appreciate any help!Anjali Parmarhttps://se.mathworks.com/matlabcentral/profile/authors/17257030-anjali-parmartag:se.mathworks.com,2005:Question/5061842020-02-18T14:10:35Z2020-02-19T00:33:48ZHow can I reduce periodic noises from my image? Please helpI've tried to reduce the periodic noises with frequency domain filtering.However, the result of the filter is not that good.Actually, even when I get fftshift of the image, I cannot see clearly noises (maybe there are four point that seems like noises, so I chose them in the code below).Please help me about this filtering.I don't have so much time.I am new at image processing btw.I thought that I can use Notch filter but I couldn't find any special function for it unlike median or average filters.
(The image is attached)
I = imread('woman-1_3.bmp');
I2=fft2(I);
imshow(log(1+abs(fftshift(I2))),[]);
m=ones(200,200);
m(84:1:92,85:1:93)=0;
m(109:1:117,85:1:93)=0;
m(84:1:92,109:1:117)=0;
m(109:1:117,109:1:117)=0;
imshow(m);
imshow(log(1+abs( fftshift(I2).*m)),[]);
imshow(log(1+abs(ifft2( fftshift(I2).*m))),[]);Ayberk Ayhttps://se.mathworks.com/matlabcentral/profile/authors/11090806-ayberk-aytag:se.mathworks.com,2005:Question/5042782020-02-07T20:19:23Z2020-02-19T00:32:35Zhello, how to make a program of aggregate blending in matlab?Hello, just need directions how can i make an executable program on aggregate blending?
Umair Masoodhttps://se.mathworks.com/matlabcentral/profile/authors/17479948-umair-masoodtag:se.mathworks.com,2005:Question/5062722020-02-18T22:03:45Z2020-02-19T00:28:52ZHow to avoid a for loop in functions?Hi All,
I have the following for loop in my matlab code and I was wandering is there any effcient way to implement this than using a for loop and going through each element.
press = 0:5/1000:5;
PsolWB = [];
for i = 1:length(press)
if (press(i)<=1.6)
PsolWB(i) = (973.-(70400./(1000.*press(i)+354.))+(77800000./(1000.*press(i)+354.).^2.)-273.15);
else
PsolWB(i)=(935.+3.5.*press(i)+6.2.*press(i).^2-273.15);
end
end
Prasannahttps://se.mathworks.com/matlabcentral/profile/authors/1752223-prasannatag:se.mathworks.com,2005:Question/5051452020-02-12T17:36:14Z2020-02-19T00:25:28ZEdit the labels in Ground Truth Image Labeler.I had used the Ground Truth Image Labeler app before to label some images for pixel level segmentaion experiment using matlab 2018b. Now I am trying to edit those labels , for instance add another category to all of them but I am having a problem in loading them properly. good news is I still have the Images and the labels , bad news is I am confused with the gtruth mat file and how to recover the session . when I try to use Load>session> and choose the gTruth file I recieve this error message
' E:/ gTruth. mat' is not a valid Ground Truth Labeler session MAT file.
My questions are :
1- Can I recover the old session from Images+Labels only? or how van i creat a new session using those iamges and labels so i dont have to re-do all the labeling work again?
2- Can I use the same step above with different version of Matlab , say Matlab 2019B?
thanks caesarhttps://se.mathworks.com/matlabcentral/profile/authors/7647654-caesartag:se.mathworks.com,2005:Question/4897002019-11-06T05:00:00Z2020-02-19T00:24:43ZIs MATLAB compatible with macOS Catalina?Does MATLAB support macOS Catalina (10.15)?
MathWorks Support Teamhttps://se.mathworks.com/matlabcentral/profile/authors/4622813-mathworks-support-teamtag:se.mathworks.com,2005:Question/5062922020-02-19T00:13:11Z2020-02-19T00:13:11ZUnable to perform assignment because the left and right sides have a different numberclc
clear
close all
% Problem Statement
Npar = 17;
VarLow=0.1;
VarHigh = 35;
%BBBC parameters
N=50; %number of candidates
MaxIter=100; %number of iterations
% initialize a random value as best value
XBest = rand(1,Npar).* (VarHigh - VarLow) + VarLow;
FBest=fitnessFunc(XBest);
GB=FBest;
t = cputime;
%intialize solutions and memory
X = zeros(N, Npar);
F = zeros(N, 1);
for ii = 1:N
X(ii,:) = rand(1,Npar).* (VarHigh - VarLow) + VarLow;
% calculate the fitness of solutions
F(ii) = fitnessFunc(X(ii,:));
end
%Main Loop
for it=1:MaxIter
%Find the centre of mass
%-----------------------
%numerator term
num=zeros(1,Npar);
for ii=1:N
for jj=1:Npar
num(jj)=num(jj)+(X(ii,jj)/F(ii));
end
end
%denominator term
den=sum(1./F);
%centre of mass
Xc=num/den;
%generate new solutions
%----------------------
for ii=1:N
%new solution from centre of mass
for jj=1:Npar
New=X(ii,:);
New(jj)=Xc(jj)+((VarHigh(jj)*rand)/it^2);
end
%boundary constraints
New=limiter(New,VarHigh,VarLow);
%new fitness
newFit=fitnessFunc(New);
%check whether the solution is better than previous solution
if newFit<F(ii)
X(ii,:)=New;
F(ii)=newFit;
if F(ii)<FBest
XBest=X(ii,:);
FBest=F(ii);
end
end
end
% store the best value in each iteration
GB=[GB FBest];
end
t1=cputime;
fprintf('The time taken is %3.2f seconds \n',t1-t);
fprintf('The best value is :');
XBest
FBest
% Convergence Plot
figure(1)
plot(0:MaxIter,GB, 'linewidth',1.2);
title('Convergence');
xlabel('Iterations');
ylabel('Objective Function (Cost)');
grid('on')
function newP=limiter(P,VarHigh,VarLow)
% LIMITER Function to perfrom range limit operation on the solution
% to be within the search space bounds
newP=P;
for i=1:length(P)
if newP(i)>VarHigh(i)
newP(i)=VarHigh(i);
elseif newP(i)<VarLow(i)
newP(i)=VarLow(i);
end
end
end
function fit=main1(X)
global X;
global fit;
for ii=1:17
w=0;
L=[100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100;100];
D=[0.268;0.268;0.268;0.268;0.268;0.268;0.268;0.268;0.268;0.268;0.268;0.268;0.268;0.268;0.268;0.268;0.268];
Li=L(ii);
Di=D(ii);
Xi=X(ii);
fit=w+Xi*Li*Di;
end
end
function penalty=main2(X)
global X;
global fit ;
global penalty;
E=[30000000;30000000;30000000;30000000;30000000;30000000;30000000;30000000;30000000;30000000;30000000;30000000;30000000;30000000;30000000;30000000;30000000];
XE=X*E
NodeCoordinate=[0 0;0 100;100 0;100 100;200 0;200 100;300 0;300 100;400 0];
elementNode=[2 4;2 3;1 3;3 4;4 6; 4 5; 3 5; 5 6; 6 8; 6 7; 5 7; 7 8; 8 9; 7 9;1 4;3 6; 5 8];
numberNode=size(NodeCoordinate,1)
numberelement=size(elementNode,1)
Dof=2*numberNode
Kg=zeros(Dof)
Fg=zeros(Dof,1)
Ug=zeros(Dof,1)
for e1=1:numberelement
n1=elementNode(e1,1)
n2=elementNode(e1,2)
x1=NodeCoordinate(n1,1)
y1=NodeCoordinate(n1,2)
x2=NodeCoordinate(n2,1)
y2=NodeCoordinate(n2,2)
theta=atan2(y2-y1,x2-x1)
L=sqrt((x2-x1)^2+(y2-y1)^2)
C=(x2-x1)/L
S=(y2-y1)/L
ke1=(X*E/L)*[C^2 C*S -C^2 -C*S ;
C*S S^2 -C*S -S^2 ;
-C^2 -C*S C^2 C*S ;
-C*S -S^2 C*S S^2 ]
k1=2*n1-1;k2=2*n1;
k3=2*n2-1;k4=2*n2;
Kg(k1:k2,k1:k2) =Kg(k1:k2,k1:k2)+ke1(1:2,1:2);
Kg(k1:k2,k3:k4) =Kg(k1:k2,k3:k4)+ke1(1:2,3:4);
Kg(k3:k4,k1:k2) =Kg(k3:k4,k1:k2)+ke1(3:4,1:2);
Kg(k3:k4,k3:k4) =Kg(k3:k4,k3:k4)+ke1(3:4,3:4);
end
Kg
k = [Kg(5:18,5:18)]
f=[0;0;0;0;0;0;0;0;0;0;0;0;0;-100000]
u=k\f
Ug=[0;0;0;0;u(1:14)]
Fg=Kg*Ug
u1=[Ug(3);Ug(4);Ug(7);Ug(8)]
u2=[Ug(3);Ug(4);Ug(5);Ug(6)]
u3=[Ug(1);Ug(2);Ug(5);Ug(6)]
u4=[Ug(5);Ug(6);Ug(7);Ug(8)]
u5=[Ug(7);Ug(8);Ug(11);Ug(12)]
u6=[Ug(7);Ug(8);Ug(9);Ug(10)]
u7=[Ug(5);Ug(6);Ug(9);Ug(10)]
u8=[Ug(9);Ug(10);Ug(11);Ug(12)]
u9=[Ug(11);Ug(12);Ug(15);Ug(16)]
u10=[Ug(11);Ug(12);Ug(13);Ug(14)]
u11=[Ug(9);Ug(10);Ug(13);Ug(14)]
u12=[Ug(13);Ug(14);Ug(15);Ug(16)]
u13=[Ug(15);Ug(16);Ug(17);Ug(18)]
u14=[Ug(13);Ug(14);Ug(17);Ug(18)]
u15=[Ug(1);Ug(2);Ug(7);Ug(8)]
u16=[Ug(5);Ug(6);Ug(11);Ug(12)]
u17=[Ug(9);Ug(10);Ug(15);Ug(16)]
%strease in each elemnt
for e1=1
n1=elementNode(e1,1)
n2=elementNode(e1,2)
x1=NodeCoordinate(n1,1)
y1=NodeCoordinate(n1,2)
x2=NodeCoordinate(n2,1)
y=NodeCoordinate(n2,2)
theta=atan2(y2-y1,x2-x1)
L1=sqrt((x2-x1)^2+(y2-y1)^2)
C=(x2-x1)/L1
S=(y2-y1)/L1
sigma1=E/L1*[-C -S C S]*u1
end
for el= 2
n1=elementNode(e1,1)
n2=elementNode(e1,2)
x1=NodeCoordinate(n1,1)
y1=NodeCoordinate(n1,2)
x2=NodeCoordinate(n2,1)
y=NodeCoordinate(n2,2)
theta=atan2(y2-y1,x2-x1)
L2=sqrt((x2-x1)^2+(y2-y1)^2)
C=(x2-x1)/L2
S=(y2-y1)/L2
sigma2=E/L2*[-C -S C S]*u2
end
for e1=3
n1=elementNode(e1,1)
n2=elementNode(e1,2)
x1=NodeCoordinate(n1,1)
y1=NodeCoordinate(n1,2)
x2=NodeCoordinate(n2,1)
y=NodeCoordinate(n2,2)
theta=atan2(y2-y1,x2-x1)
L3=sqrt((x2-x1)^2+(y2-y1)^2)
C=(x2-x1)/L3
S=(y2-y1)/L3
sigma3=E/L3*[-C -S C S]*u3
end
for e1=4
n1=elementNode(e1,1)
n2=elementNode(e1,2)
x1=NodeCoordinate(n1,1)
y1=NodeCoordinate(n1,2)
x2=NodeCoordinate(n2,1)
y=NodeCoordinate(n2,2)
theta=atan2(y2-y1,x2-x1)
L4=sqrt((x2-x1)^2+(y2-y1)^2)
C=(x2-x1)/L4
S=(y2-y1)/L4
sigma4=E/L4*[-C -S C S]*u4
end
for e1=5
n1=elementNode(e1,1)
n2=elementNode(e1,2)
x1=NodeCoordinate(n1,1)
y1=NodeCoordinate(n1,2)
x2=NodeCoordinate(n2,1)
y=NodeCoordinate(n2,2)
theta=atan2(y2-y1,x2-x1)
L5=sqrt((x2-x1)^2+(y2-y1)^2)
C=(x2-x1)/L5
S=(y2-y1)/L5
sigma5=E/L5*[-C -S C S]*u5
end
for e1=6
n1=elementNode(e1,1)
n2=elementNode(e1,2)
x1=NodeCoordinate(n1,1)
y1=NodeCoordinate(n1,2)
x2=NodeCoordinate(n2,1)
y=NodeCoordinate(n2,2)
theta=atan2(y2-y1,x2-x1)
L6=sqrt((x2-x1)^2+(y2-y1)^2)
C=(x2-x1)/L6
S=(y2-y1)/L6
sigma6=E/L6*[-C -S C S]*u6
end
for e1=7
n1=elementNode(e1,1)
n2=elementNode(e1,2)
x1=NodeCoordinate(n1,1)
y1=NodeCoordinate(n1,2)
x2=NodeCoordinate(n2,1)
y=NodeCoordinate(n2,2)
theta=atan2(y2-y1,x2-x1)
L7=sqrt((x2-x1)^2+(y2-y1)^2)
C=(x2-x1)/L7
S=(y2-y1)/L7
sigma7=E/L7*[-C -S C S]*u7
end
for e1=8
n1=elementNode(e1,1)
n2=elementNode(e1,2)
x1=NodeCoordinate(n1,1)
y1=NodeCoordinate(n1,2)
x2=NodeCoordinate(n2,1)
y=NodeCoordinate(n2,2)
theta=atan2(y2-y1,x2-x1)
L8=sqrt((x2-x1)^2+(y2-y1)^2)
C=(x2-x1)/L8
S=(y2-y1)/L8
sigma8=E/L8*[-C -S C S]*u8
end
for e1=9
n1=elementNode(e1,1)
n2=elementNode(e1,2)
x1=NodeCoordinate(n1,1)
y1=NodeCoordinate(n1,2)
x2=NodeCoordinate(n2,1)
y=NodeCoordinate(n2,2)
theta=atan2(y2-y1,x2-x1)
L9=sqrt((x2-x1)^2+(y2-y1)^2)
C=(x2-x1)/L9
S=(y2-y1)/L9
sigma9=E/L9*[-C -S C S]*u9
end
for e1=10
n1=elementNode(e1,1)
n2=elementNode(e1,2)
x1=NodeCoordinate(n1,1)
y1=NodeCoordinate(n1,2)
x2=NodeCoordinate(n2,1)
y=NodeCoordinate(n2,2)
theta=atan2(y2-y1,x2-x1)
L10=sqrt((x2-x1)^2+(y2-y1)^2)
C=(x2-x1)/L10
S=(y2-y1)/L10
sigma10=E/L*[-C -S C S]*u10
end
for e1=11
n1=elementNode(e1,1)
n2=elementNode(e1,2)
x1=NodeCoordinate(n1,1)
y1=NodeCoordinate(n1,2)
x2=NodeCoordinate(n2,1)
y=NodeCoordinate(n2,2)
theta=atan2(y2-y1,x2-x1)
L11=sqrt((x2-x1)^2+(y2-y1)^2)
C=(x2-x1)/L11
S=(y2-y1)/L11
sigma11=E/L11*[-C -S C S]*u11
end
for e1=12
n1=elementNode(e1,1)
n2=elementNode(e1,2)
x1=NodeCoordinate(n1,1)
y1=NodeCoordinate(n1,2)
x2=NodeCoordinate(n2,1)
y=NodeCoordinate(n2,2)
theta=atan2(y2-y1,x2-x1)
L12=sqrt((x2-x1)^2+(y2-y1)^2)
C=(x2-x1)/L12
S=(y2-y1)/L12
sigma12=E/L12*[-C -S C S]*u12
end
for e1=13
n1=elementNode(e1,1)
n2=elementNode(e1,2)
x1=NodeCoordinate(n1,1)
y1=NodeCoordinate(n1,2)
x2=NodeCoordinate(n2,1)
y=NodeCoordinate(n2,2)
theta=atan2(y2-y1,x2-x1)
L13=sqrt((x2-x1)^2+(y2-y1)^2)
C=(x2-x1)/L13
S=(y2-y1)/L13
sigma13=E/L13*[-C -S C S]*u13
end
for e1=14
n1=elementNode(e1,1)
n2=elementNode(e1,2)
x1=NodeCoordinate(n1,1)
y1=NodeCoordinate(n1,2)
x2=NodeCoordinate(n2,1)
y=NodeCoordinate(n2,2)
theta=atan2(y2-y1,x2-x1)
L14=sqrt((x2-x1)^2+(y2-y1)^2)
C=(x2-x1)/L14
S=(y2-y1)/L14
sigma14=E/L14*[-C -S C S]*u14
end
for e1=15
n1=elementNode(e1,1)
n2=elementNode(e1,2)
x1=NodeCoordinate(n1,1)
y1=NodeCoordinate(n1,2)
x2=NodeCoordinate(n2,1)
y=NodeCoordinate(n2,2)
theta=atan2(y2-y1,x2-x1)
L15=sqrt((x2-x1)^2+(y2-y1)^2)
C=(x2-x1)/L15
S=(y2-y1)/L15
sigma15=E/L15*[-C -S C S]*u15
end
for e1=16
n1=elementNode(e1,1)
n2=elementNode(e1,2)
x1=NodeCoordinate(n1,1)
y1=NodeCoordinate(n1,2)
x2=NodeCoordinate(n2,1)
y=NodeCoordinate(n2,2)
theta=atan2(y2-y1,x2-x1)
L16=sqrt((x2-x1)^2+(y2-y1)^2)
C=(x2-x1)/L16
S=(y2-y1)/L16
sigma16=E/L16*[-C -S C S]*u16
end
for e1=17
n1=elementNode(e1,1)
n2=elementNode(e1,2)
x1=NodeCoordinate(n1,1)
y1=NodeCoordinate(n1,2)
x2=NodeCoordinate(n2,1)
y=NodeCoordinate(n2,2)
theta=atan2(y2-y1,x2-x1)
L17=sqrt((x2-x1)^2+(y2-y1)^2)
C=(x2-x1)/L17
S=(y2-y1)/L17
sigma17=E/L17*[-C -S C S]*u17
end
sigma1;
sigma2;
sigma3;
sigma4;
sigma5;
sigma6;
sigma7;
sigma8;
sigma9;
sigma10;
sigma11;
sigma12;
sigma13;
sigma14;
sigma15;
sigma16;
sigma17;
for ii=1:17
N=0;
S=[sigma1;sigma2;sigma3;sigma4;sigma5;sigma6;sigma7;sigma8;sigma9;sigma10;sigma11;sigma12;sigma13;sigma14;sigma15;sigma16;sigma17];
TM=[50000;50000;50000;50000;50000;50000;50000;50000;50000;50000;50000;50000;50000;50000;50000;50000;50000];
Si=S(ii);
TMi=TM(ii);
if -(TMi)<= Si <= (TMi)
F= 0;
else
F= abs((Si)/(TMi))-1;
end
N=N+sum(F);
end
for ii=1:18
H=0;
U=Ug
DM=[2;2;2;2;2;2;2;2;2;2;2;2;2;2;2;2;2;2;2;2];
Ui=U(ii);
DMi=DM(ii);
if -(DMi) <= Ui <= (DMi)
A= 0;
else
A= abs((Ui)/(DMi))-1;
end
H=H+sum(A);
end
J=sum(N)+sum(H);
K=0.9
penalty=K*J*fit;
end
function fitness = fitnessFunc(X)
global fit;
global penalty;
fitness=penalty+fit;
end
Unable to perform assignment because the left and right sides have a different number .Can any one help me with this [ F(ii) = fitnessFunc(X(ii,:));]sura najihttps://se.mathworks.com/matlabcentral/profile/authors/17541214-sura-najitag:se.mathworks.com,2005:Question/5050962020-02-12T13:56:05Z2020-02-19T00:08:19ZMUSIC algorithm ghost target in Matlab Radar Simulation DemoI am using MUSIC algorithm for radar angle estimation project. However, it will show a mirror target when the target is near the angle limit. I found the same issue in the Radar Signal Simulation and Processing for Automated Driving demo.
Can anyone explain this to me? Or how can we solve this issue in tracking?
mk14https://se.mathworks.com/matlabcentral/profile/authors/8094564-mk14tag:se.mathworks.com,2005:Question/5060512020-02-17T21:53:49Z2020-02-18T23:57:18ZI can't figure out how to ask for the number of resistors that has to be an integer up to 10 and then use a loop to enter R1, R2, ... RnMy homework says to ask if the combination is in series or parallel and I believe I have that done but then I need it to ask for the number of resistors (integer up to 10) and also use a loop to enter R1, R2, ...Rn
So far I have
C=input('Input if the combination is in series or parallel: ','series','parallel');
n=input('Enter the number or resistors');
>> while n=int32(n)
n=input('Enter the number of resistors: ');
fprintf('Enter an integer up to 10')
end
I'm not sure if this is even right for n and can't figure out how to ask the user to input value for R1, R2...Bryce Meyerhttps://se.mathworks.com/matlabcentral/profile/authors/17243236-bryce-meyertag:se.mathworks.com,2005:Question/5062612020-02-18T20:51:19Z2020-02-18T23:28:58ZHow do you use ./ operator on array of custom classHi,
I've written a custom class with overloads for mathematical operators. I now have arrays a and b and I want to do element-wise division.
My first guess was that the ./ operator would map the / operator over the elements of the array, however with mrdivide defined I get the error "Undefined operator './' for input arguments of type".
When I add the following code to my class
function r = rdivide(a, b)
for i = 1:length(a)
r(i) = a / b
end
end
I get the error "Error using / Too many input arguments" with line numbers pointing into my mrdivide function. My mrdivide function seems to work when I use it on its own.
Is this the correct way to implement element-wise division?
Thanks.Jefferson Carpenterhttps://se.mathworks.com/matlabcentral/profile/authors/17326551-jefferson-carpentertag:se.mathworks.com,2005:Question/5062852020-02-18T22:52:42Z2020-02-18T23:25:33Zeuler function that you can reuse with different values?function [t, y, yprime]=euler(f,t0,tN,y0,N)
h=(tN-t0)/N;
t=t0:N:tN;
y=zeros(1,N+1);
yprime=f(t,y);
y(1)=y0;
t(1)=t0;
for i=1:N
t=(i-1)*h;
y(i)=y(i)+h*(f(y(i),t(i)));
end
end
this is my code for a euler method function. I cant seem to get it to run properly. Any ideas on what i am doing wrong. please help!
[SL: formatted function as code]Benjamin Trivershttps://se.mathworks.com/matlabcentral/profile/authors/17203739-benjamin-triverstag:se.mathworks.com,2005:Question/5062902020-02-18T23:10:46Z2020-02-18T23:16:06ZHow to find wavelength of a surface that I have generated using fft2?Hi, I have a surface profile like the first image. I performed fft2 to find the second image. x and y-axes values are in pixels. I have 2 questions.
What does the second image mean physically?
Most importantly, how to find the wavelength present in the surface?
Mustafa Rifathttps://se.mathworks.com/matlabcentral/profile/authors/10775811-mustafa-rifattag:se.mathworks.com,2005:Question/5047352020-02-10T20:35:19Z2020-02-18T23:10:21Zerror in plotting Index in position 2 exceeds array bounds.Hello
Im quite new to matlab
currently im trying to plot as in
https://uk.mathworks.com/help/stats/classificationecoc.html
using dataset from
https://www.kaggle.com/uciml/human-activity-recognition-with-smartphones
my code is below
clear; close all; clc;
T = readtable('train.csv');
X = T(:,(1:562));
Y = T(:,{'Activity'});
t = templateSVM('Standardize',true,'SaveSupportVectors',true);
predictorNames = {'alfa','beta'};
responseName = 'Human Activity';
classNames = {'STANDING','SITTING','LAYING','WALKING','WALKING_DOWNSTAIRS','WALKING_UPSTAIRS'}; % Specify class order
Mdl = fitcecoc(X,Y);
Mdl.ClassNames
Mdl.CodingMatrix
L = size(Mdl.CodingMatrix,6); % Number of SVMs
sv = cell(L,1); % Preallocate for support vector indices
for j = 1:L
SVM = Mdl.BinaryLearners{j};
sv{j} = SVM.SupportVectors;
sv{j} = sv{j}.*SVM.Sigma + SVM.Mu;
end
hold on
markers = {'ko','ko','ko','ko','ko','ko','ko'}; % Should be of length L
for j = 1:L
svs = sv{j};
plot(svs(:,1),svs(:,2),markers{j},...
'MarkerSize',10 + (j - 1)*3);
end
title('Fisher''s Iris -- ECOC Support Vectors')
xlabel(predictorNames{1})
ylabel(predictorNames{2})
legend([classNames,{'Support vectors - SVM 1',...
'Support vectors - SVM 2','Support vectors - SVM 3'}],...
'Location','Best')
hold off
unfortunettly im getting error
Index in position 2 exceeds array bounds.Index in position 2 exceeds array bounds.
Error in learningmulticlasCVN (line 35)
plot(svs(:,1),svs(:,2),markers{j},..
Tomasz Kaczmarskihttps://se.mathworks.com/matlabcentral/profile/authors/17173063-tomasz-kaczmarskitag:se.mathworks.com,2005:Question/3789412018-01-25T13:18:11Z2020-02-18T23:09:40ZMatlab code for Optimization of Distributed GenerationMatlab code for Optimization of Distributed GenerationRespect Every Onehttps://se.mathworks.com/matlabcentral/profile/authors/11983263-respect-every-onetag:se.mathworks.com,2005:Question/5062892020-02-18T23:02:46Z2020-02-18T23:02:46Zsplitting up a timeseries into separate componentshi all!
I am trying to seperate chunks of a timeseries into sleep vs. wake components.
I'm having problems with two things:
1) I've figured out how to do it with one section, but I want to be able to do it with multiple sections, e.g. 200-600 seconds and 750-800 seconds.
2) I also want to take these chunks of the timeseries and then calculate the power. When I try to run my script to calculate the power, I get a ton of errors I think because sleep_c (etc) is = 1x1 double times, rather than my normal ts = 1000x1 double
thanks times a million:
I've done this:
%%%%loading
sleep_behavior = 1500:3000
sleep_c = timeseries(d_c_ts_1(sleep_behavior,1), 1500:3000,'name', 'fMRI signal')
sleep_behavior = 1500:3000
sleep_v = timeseries(d_v_ts_1(sleep_behavior,1), 1500:3000,'name', 'fMRI signal')
wake_behavior = 100:200
wake_c = timeseries(d_c_ts_1(wake_behavior,1), 100:200,'name', 'fMRI signal')
wake_behavior = 100:200
wake_v = timeseries(d_v_ts_1(wake_behavior,1), 100:200,'name', 'fMRI signal')
%% calculating power of sleep vs. wake ----- power vs. frequency
for a = 1:1
name = sleep_v
[power_sleep_v, f] = mtspectrumc(name,params) %detrended cortex young person
end
nineshttps://se.mathworks.com/matlabcentral/profile/authors/15883041-ninestag:se.mathworks.com,2005:Question/5062872020-02-18T23:00:19Z2020-02-18T23:00:19ZIndex exceeds the number of array elements (1).clear
close all
% Problem Statement
Npar = 17;
VarLow=0.1;
VarHigh = 35;
%BBBC parameters
N=50; %number of candidates
MaxIter=100; %number of iterations
% initialize a random value as best value
XBest = rand(1,Npar).* (VarHigh - VarLow) + VarLow;
FBest=fitnessFunc(XBest);
GB=FBest;
t = cputime;
%intialize solutions and memory
X = zeros(N, Npar);
F = zeros(N, 1);
for ii = 1:N
X(ii,:) = rand(1,Npar).* (VarHigh - VarLow) + VarLow;
% calculate the fitness of solutions
F(ii) = fitnessFunc(X(ii,:));
end
%Main Loop
for it=1:MaxIter
%Find the centre of mass
%-----------------------
%numerator term
num=zeros(1,Npar);
for ii=1:N
for jj=1:Npar
num(jj)=num(jj)+(X(ii,jj)/F(ii));
end
end
%denominator term
den=sum(1./F);
%centre of mass
Xc=num/den;
%generate new solutions
%----------------------
for ii=1:N
%new solution from centre of mass
for jj=2:Npar
New=X(ii,:);
New(jj)=Xc(jj)+((VarHigh(jj)*rand)/it^2);
end
%boundary constraints
New=limiter(New,VarHigh,VarLow);
%new fitness
newFit=fitnessFunc(New);
%check whether the solution is better than previous solution
if newFit<F(ii)
X(ii,:)=New;
F(ii)=newFit;
if F(ii)<FBest
XBest=X(ii,:);
FBest=F(ii);
end
end
end
% store the best value in each iteration
GB=[GB FBest];
end
%Main Loop
for it=1:MaxIter
%Find the centre of mass
%-----------------------
%numerator term
num=zeros(1,Npar);
for ii=1:N
for jj=1:Npar
num(jj)=num(jj)+(X(ii,jj)/F(ii));
end
end
%denominator term
den=sum(1./F);
%centre of mass
Xc=num/den;
%generate new solutions
%----------------------
for ii=1:N
%new solution from centre of mass
for jj=2:Npar
New=X(ii,:);
New(jj)=Xc(jj)+((VarHigh(jj)*rand)/it^2);
end
Hi please can someone help me the code runs perfectly on my computer, but when transferred to another and ran, it gives the error message (index exceeds the number of array elements (1))? And error in this line New(jj)=Xc(jj)+((VarHigh(jj)*rand)/it^2);sura najihttps://se.mathworks.com/matlabcentral/profile/authors/17541214-sura-najitag:se.mathworks.com,2005:Question/5062842020-02-18T22:50:37Z2020-02-18T22:50:37ZSimulating Freespace power in MatlabCan someone help me figure out how to write this MATLAB code? I'm looking for some example code to get started. The scope of what I want to do is below.
scope:
Simulate free space power available at several mobile frequencies in Matlab. Consider frequency range from 800MHz to 3 GHz. You can evaluate the loss occurred for three different distances: short distance 100m, midium distance 1Km, and large distance 10 Km. Plot all the loss Vs distance graph in single maltlab plot. Use appropriate axis, grid, legends, and color to represent it on plot.
There are other radio attenuating factors such as rain, fog, high humidity level etc. These factors play important role at higher operating frequnecies. Typically, rain attenuation is extreme at Radar or Satellite communication greater than 5 GHz. A Light rain cause only about 0.01dB attenuation loss while 0.4dB atttenuation loss due to high rain at 10 GHz carrier frequency.Nathan Jaquahttps://se.mathworks.com/matlabcentral/profile/authors/16087556-nathan-jaquatag:se.mathworks.com,2005:Question/5062632020-02-18T21:00:29Z2020-02-18T22:46:24ZExcel data set to vectorsHi im new to matlab. I have importet numerical matrix 299x4 from excel to matlab and devided it to x1, x2, y1 and y2 values:
But how do i make vectors from x1,y1, x2 and y2 values and then plot them. Like on this picture:
Bartosz Chmarzynskihttps://se.mathworks.com/matlabcentral/profile/authors/17570339-bartosz-chmarzynskitag:se.mathworks.com,2005:Question/5050532020-02-12T10:37:00Z2020-02-18T22:45:57ZRadar Doppler Signals for Car dataset!!Matlab provides a dataset for Pedestrain and Bicycle doppler signals, which is used for Deep Learning. The car signal is used for noise. I want to classify Bicycle and Car instead, hence need a dataset for Car. Is there any way I can make a dataset for Car using Doppler Signals within Matlab?
Matlab have in-built backscatterPedestrain and backscatterBicycle function, which is used to move and recieve signals from Pedestrain and Bicycles respectively. I tried to change the function but could not do it since many commands are in build within that function. Anyone ?
Muhammad Fayyazhttps://se.mathworks.com/matlabcentral/profile/authors/11683032-muhammad-fayyaztag:se.mathworks.com,2005:Question/5062762020-02-18T22:14:30Z2020-02-18T22:43:55Z2D Temperature Distribution I need to plot the temperature distribution for the square cross-section of a bar, 3 sides are fixed at a temperature of 283 K, the fourth side at 508 K and the initial temperature of the interior is 307 K everwhere. The analytical solution is as follows:
L and W are both equal to 1, and the summation is done from n =1 to n =100. Here is what I have done so far, I've tried to make 100 10 x 10 grids and populate each element with values for theta and then sum all the grids to give a final 10 x 10 grid for the temperature distribution. I don't really understand how to execute this with for loops, thanks for any help.
X = 10;
Y = 10;
theta1 = zeros (X,Y);
for n =1:100
for X1 = 1:X
for Y1 = 1:Y
theta1(n,X1,Y1)=(2/pi)*(((-1)^(n+1)+1)/(n))*sin(n*pi*X1/L)*(sinh(n*pi*Y1/L))/(sinh(n*pi*W/L));
end
end
end
theta1sum = sum(theta1);
Jonathan Birdhttps://se.mathworks.com/matlabcentral/profile/authors/12020233-jonathan-birdtag:se.mathworks.com,2005:Question/5062832020-02-18T22:40:05Z2020-02-18T22:40:05Z"index exceeds matrix dimensions" using simulinkthe following code is in regards to rotational sytem with three storing elements using simulink to plot for angular velocities an torque. after y_out(:,1) however, it keeps showing that the index exceeds matrix dimensions. Any help? simulink file is attached
clc
clear all
m1=1;
m2=3; %this is the mass in kg
k=330;
r1=.03;
r2=.1;
b=.2;
J1=.5*m1*r2^2;
J2 = J1;
N=r2/r1;
A = [0 1 -1 ;-k/J1 0 0; k/J2 0 -b/J2];
B = [0 ; N/J1 ;0];
C=[0 0 1];
D=[0]';
x0= [0]';
tf=30;
t1 = [0:0.01:tf];
%t1 = [0:0.01:1]
F = 10 ;
u=F*ones(size(t1));
%u=F*cos(t1)
sim('HW2_SimLink')
cart_po = y_out(:,1);
cart_vel = y_out(:,2);
cart_po1 = y_out(:,3);
cart_vel1 = y_out(:,4);
figure(1)
plot(t1,cart_po,'-b','linewidth',1.5)
xlabel('Time (seconds)','fontsize',14)
ylabel('Position m1 (m)','fontsize',14)
grid,
figure(2)
plot(t1,cart_vel,'-r','linewidth',1.5);
%legend('Position','Velocity')
xlabel('Time (seconds)','fontsize',14)
ylabel('Velocity m1 (m/s)','fontsize',14)
grid, hold
figure(3)
plot(t1,cart_po1,'-g','linewidth',1.5)
xlabel('Time (seconds)','fontsize',14)
ylabel('Position m2 (m)','fontsize',14)
grid, hold
figure(4)
plot(t1,cart_vel1,'-k','linewidth',1.5);
%legend('Position','Velocity')
xlabel('Time (seconds)','fontsize',14)
ylabel('Velocity m2 (m/s)','fontsize',14)
grid, hold
Osmar Sanchezhttps://se.mathworks.com/matlabcentral/profile/authors/9581666-osmar-sancheztag:se.mathworks.com,2005:Question/5062582020-02-18T20:45:00Z2020-02-18T22:39:22ZInterpolation data to achieve gridded latitude and longitude when I have 360 monthHey all,
I have a table that has four columns (longitude, latitude, date, and observed_value). In my table latitude and longitude values represent 95 unique locations that are scattered randomly. Each one for 360 months; I mean I have 360 observed_value data for each unique location from like 1/1/1989, 2/1/1989, 3/1989, ... 12/1/2018. I want to convert this scattered data to gridded data by interpolation. I want to have data for longitude = 44.25:.5:63.75 and latitude: 24.25:.5:39.75 for each month. So, in the end, I will have so many locations rather than 95 (for example 11000) that have observed_data for these 360 months.
I have been thought about it for 2 days I really search for everything but I don't know how can I do this. I want to ask you please help me with the issue. If it is important, after that I want to make 1 x n cell which each array in it is a table for these gridded data locations for each month.
If you have any additional questions or require further clarification, please, do not hesitate to tell me.
I attached my table, any advice is highly appreciated, Thank you.
Behzad Navidihttps://se.mathworks.com/matlabcentral/profile/authors/15525777-behzad-naviditag:se.mathworks.com,2005:Question/5062822020-02-18T22:39:22Z2020-02-18T22:39:22ZReading out current url with Matlab on LinuxHi everyone,
I am trying to run a Qualtrics survey using a Matlab script. Participants are supposed to answer the survey and then go on with the task that is provided in the script. The problem is that Matlab needs to know when the participant is finished. My first attempt was to use Matlab's web command [stat,h,url] = web(___) to open the survey, then letting the script circle in a loop, checking for the current url using get(h, 'CurrentLocation') and if that url equals the url that Qualtrics redirects to after the survey is finished, it closes the browser and goes on.
The problem now is that this works fine on a computer with Windows, but not on Linux. I can open different webpages, but not Qualtrics, and also other websites look blunt and not correctly presented. I can open everything using the system browser, but then I do not get the current url.
My questions now:
Is there a common issue on Linux with Matlab's web browser and is there a way to fix it?
Is there a way to read the current url using the system browser?
Is there another way that Qualtrics could tell Matlab when the survey is finished (that might not be the ideal place to ask that, but I do it just in case)?
Thank you for any help!Finn Luebberhttps://se.mathworks.com/matlabcentral/profile/authors/16057478-finn-luebbertag:se.mathworks.com,2005:Question/5061762020-02-18T13:03:06Z2020-02-18T22:37:15ZScatter Plot with different "markers" and "data labels"a=[32.0 30.0 29.0 42.0 61.0 81.0]
b=[0.9 0.8 0.2 0.4 0.3 0.10]
c={'US'; 'GM'; 'SA'; 'IN'; 'EG'; 'BZ'}
scatter(a,b)
xlim([0 50])
ylim([0 1])
refline
grid
I need a "scatter plot" with different "markers" and "data labels" (array in c). Also the refline should always start from (zero,zero)Muhammad Rahil Rafiqhttps://se.mathworks.com/matlabcentral/profile/authors/3345592-muhammad-rahil-rafiqtag:se.mathworks.com,2005:Question/5061722020-02-18T12:32:44Z2020-02-18T22:35:37ZAbout real time data processing in FMCW RADAR.clear all;
clear all;
%read the raw data .wav file here
[Y,FS,NBITS]=wavread('Ranging_Radar_Exp');
%constants
c = 3E8; % (m/s) speed of light
%radar parameters
Tp = 20E-3; % (s) pulse time
N = Tp*FS; % # of samples per pulse
fstart = 2405E6; % (Hz) LFM start frequency
fstop = 2495E6; % (Hz) LFM stop frequency
BW = fstop-fstart; % (Hz) transmit bandwidth
f = linspace(fstart, fstop, N/2); %instantaneous transmit frequency
%range resolution
rr = c/(2*BW);
max_range = rr*N/2;
%the input appears to be inverted
trig = -1*Y(:,1);
s = -1*Y(:,2);
clear Y;
%parse the data here by triggering off rising edge of sync pulse
count = 0;
thresh = 0;
start = (trig > thresh);
for ii = 100:(size(start,1)-N)
if start(ii) == 1 & mean(start(ii-11:ii-1)) == 0
% start2(ii) =1;
count = count + 1;
sif(count,:) = s(ii:ii+N-1);
time(count) = ii*1/FS;
end
end
%subtract the average
ave = mean(sif,1);
for ii =1:size(sif,1);
sif(ii,:) = sif(ii,:)-ave;
end
zpad = 8*N/2;
%2 pulse cancelor RTI plot
figure (20);
sif2 = sif(2:size(sif,1),:)-sif(1:size(sif,1)-1:);
v = ifft(sif2,zpad,2);
S=v;
R = linspace(0,max_range,zpad);
for ii = 1:size(S,1)
%S(ii,1) = S(ii,:).*R.^(3/2); %Optional: magnitude scale to range
end
S = dbv(S(:,1:size(v,2)/2));
m = max(max(S));
imagesc(R,time,S-m,[-80, 0]);
colorbar;
ylabel('time (s)');
xlabel('range (m)');
title('RTI with 2-pulse cancelor clutter rejection');
Hi everyone.
I used windows recorder to record .wav file for doing ranging radar experiment.
I used above code for processing .wav file to ranging radar.
however I wanna making real-time FMCW radar.
so how can I modify the above matlab code?
I think that I have to get an real-time wave data from antenna.
I'll wait anyone's greatful help.AtoZhttps://se.mathworks.com/matlabcentral/profile/authors/5240757-atoztag:se.mathworks.com,2005:Question/5043962020-02-08T18:45:17Z2020-02-18T22:34:20ZMatlab range and angleAn airplane is moving with constant velocity along x-axis between two points. I need to plot range from the stationary object on the ground with position [0,250,0]. Iām using rangeangle MATLAB function to find the range and angles. I need to create a loop to plot all the points.
That what I have so far
TargetLoc = [0;-250;0];%target location
Origin = [-2000;0;450]; %start point
mph=45;%velocity in miles per hour
d=linspace(-2000,2000,200);% total distance travelledwith points
vel=mph*0.44704;%veloci,ty in m/s in x direction
position=d.*t;
[tgtrng, tgtang] = rangeangle(TargetLoc,Origin);
range=tgtrng
azimuth=tgtang(1)
elevation=tgtang(2)
Thanks in advance.sereksanhttps://se.mathworks.com/matlabcentral/profile/authors/4113515-sereksantag:se.mathworks.com,2005:Question/5062812020-02-18T22:34:20Z2020-02-18T22:34:20ZHelp with longitudinal car following model based on spring / damper style interactionsThis is my attempt at creating a car following model using a pedal input u to produce an acceleration/deceleration and thus a velocity using euler integration. It's in it's early days so there may be some fundamental issues, but the theory is that a pedal input u is used to scale a max accel/brake at specific vehicle speeds using a lookup table / known values. The cruise control part is ok but I can't stop the cars from driving through eachother (ie. the cars won't follow). I've tried a range of values of gains and I now suspect the theory in my logic is flawed. The script is below and any help is appreciated.
close all
clear all
%% ------------------------------------------------------------------------
%VEHICLE (acceleration lookup table
Vehicle_Mass = 1675;
Total_Force = [0, 150.3, 293.4, 466.1, 611, 757.1, 884.9, 1024, 1164, 1316, 1481, 1639, 1799, 1974, 2141, 2325, 2502, 2673, 2861, 3030, 3218, 3428, 3633, 3862, 4106, 4363, 4618, 4888, 5199, 5558, 5898, 6296, 6734, 7151, 7610, 8037, 8550, 9121, 9705, 10420, 11170, 11850, 12620, 13380, 14240, 14960, 15740, 16610, 17570, 18460, 19100, 19800, 20750, 21300, 21550, 21550, 21200, 20600, 19850, 18950, 18000, 17150, 16100, 15000, 13000];
Vehicle_Speed = [73.484, 71.9, 70.4, 68.6, 67.1, 65.6, 64.3, 62.9, 61.5, 60, 58.4, 56.9, 55.4, 53.8, 52.3, 50.7, 49.2, 47.8, 46.3, 45, 43.6, 42.1, 40.77, 39.2, 37.7, 36.2, 34.8, 33.4, 31.9, 30.3, 28.9, 27.4, 25.9, 24.6, 23.3, 22.2, 21, 19.8, 18.7, 17.5, 16.4, 15.5, 14.6, 13.8, 13, 12.4, 11.8, 11.2, 10.6, 10.1, 9.7, 9.2, 8.3, 7.4, 6.3, 5.2, 3.8, 2.9, 2.1, 1.5, 1, 0.7, 0.4, 0.2, 0];
Max_Acceleration = Total_Force/Vehicle_Mass;
Max_Deceleration = -15*ones(size(Vehicle_Speed));
%% ------------------------------------------------------------------------
figure
plot(Vehicle_Speed, Max_Acceleration, 'Color', 'r', 'LineWidth', 2)
hold on
plot(Vehicle_Speed, Max_Deceleration, 'Color', 'r', 'LineWidth', 2);
ylim([-20 15])
xlim([0 74])
line([0,0], ylim, 'Color', 'k', 'LineWidth', 2);
line(xlim, [0,0], 'Color', 'k', 'LineWidth', 2)
xlabel('Vehicle Speed (m/s)')
ylabel('Max Vehicle Acceleration (m/s^2)')
grid on
grid MINOR
%% ------------------------------------------------------------------------
N = 1000; % length of sim
h = 0.01; % timestep
cars = 5; % number of cars
in_spac = 10; % initial spacing
a = zeros(cars, N); % acceleration matrix
v = zeros(cars, N); % velocity matrix
d_euler = zeros(cars, N); % distance matrix
d = zeros(cars, N); % distance matrix
u_rec = zeros(cars, N); % input matrix
v_target = randi([22 35],cars,1); % Random values of target speed between 50-80mph
k1 = 1; % gain 1
k2 = 1; % gain 2
for i = 1:N
for j = 1:cars
if v(j,i) < 0
v(j,i) = 0.1;
end
if j == cars || i == 1
u = ( -k1 * ( v(j,i) - v_target(j) ) ); %leading car (j = 5) pedal input according to target speed only
else
u = ( -k1 * ( v(j,i) - v_target(j) ) ) + ( -k2 * ( d(j+1,i-1) - d(j,i-1) ) ); %hooks law type interaction for second term
end
%conditions to keep u between -1 and 1
if u > 1
u = 1;
elseif u < -1
u = -1;
end
if u < 0
a(j,i) = u*15; %uniform max rate deceleration at all speeds
else
a(j,i) = u*interp1(Vehicle_Speed, Max_Acceleration, v(j,i),'spline');
end
v(j,i+1) = v(j,i) + a(j,i)*h;
d_euler(j,i+1) = d_euler(j,i) + v(j,i)*h;
if i == 1
d(j,i) = j*in_spac; %setting initial spacing
else
d(j,i) = d(j,1) + d_euler(j,i);
end
u_rec(j,i) = u; %recording the pedal input
end
end
figure
subplot(4,1,1)
plot(a')
ylabel('Acceleration')
grid on
grid minor
subplot(4,1,2)
plot(v')
ylabel('Velocity')
grid on
grid minor
subplot(4,1,3)
plot(d')
ylabel('Distance')
grid on
grid minor
subplot(4,1,4)
plot(u_rec')
ylabel('u')
grid on
grid minor
pedrodiablohttps://se.mathworks.com/matlabcentral/profile/authors/8953156-pedrodiablotag:se.mathworks.com,2005:Question/5062782020-02-18T22:17:55Z2020-02-18T22:34:05ZHow to generate random integer from 1 to N except some integers in between?Suppose I want to generate unrepeated M integers between 1 and N. but except an arbitrary integer b s.t 1<= b<=N
is there any one-line command or something or do I have to construct a loop?
Thanks
Cantor Sethttps://se.mathworks.com/matlabcentral/profile/authors/14440086-cantor-settag:se.mathworks.com,2005:Question/5062752020-02-18T22:11:11Z2020-02-18T22:32:21ZMatrix consisting of sub-elements of another matrixSay I have the following matrix:
x = [ 1 2 3 4 5 6 7 8 9]
If I want a matrix that consists of the following:
y = [1 2 4 5 9]
How would I go about doing this? Articathttps://se.mathworks.com/matlabcentral/profile/authors/13321138-articattag:se.mathworks.com,2005:Question/5062802020-02-18T22:27:22Z2020-02-18T22:27:22Zmake a parameter in a reference model global simulink realtime I am using simulink realtime with a speedgoat target machine. My team has structured our model to use reference models, to better aid collaboration. We also use constant blocks that reference variables in our matlab workspace, which allows us to tune them via simulink realtime explorer or via the setparam command. https://www.mathworks.com/help/xpc/api/setparam.html
However, as we make more of our subsystems reference models we are noticing that these variables that were previously tunable when in the top model are no longer tunable via the slrtexplr or setparam. I think this because they are not considered global parameters. My question is: Is there a way to make a parameter in a reference model a global tunable parameter?
Eric Johnsonhttps://se.mathworks.com/matlabcentral/profile/authors/16264474-eric-johnsontag:se.mathworks.com,2005:Question/5060342020-02-17T19:37:07Z2020-02-18T22:26:25ZPlot straight lines between the data points in the same colour as the data points with lots of NaN valuesI'm using Matlab R2019a.
Apart from what is working so far (see code below), I would like to:
plot straight lines between the data points of the same site in chronological order in the same colour as the data points (not easy because of the NaN values)
don't loose the legend with all the sites, even if they are only NaN values for that site. (For better comparison with plots for other Chemicals)
I've data from different locations. Each "Location" has a different number of measuring "sites". These sites can be of three different types (GWM, VZ, Rain)
The data for one location is stored in a matrix.
I've created a function to be able to use the plot for Concentrations of different Chemicals. The matrix contains a lot of NaN.
set(groot, 'DefaultLineMarkerEdgeColor', 'k')
Colour=flip(colorcube(8),1); Colour=Colour(2:8,:);
Chemical = 'Nitrate';
% create random Concentration matirx with NaN values
ConcMatrix=rand(37,11); x1 = logical(randi([0, 1], [37,11])); ConcMatrix(x1==1) = [NaN];
x2 = logical(randi([0, 1], [37,11])); ConcMatrix(x2==1) = [NaN]; x3 = logical(randi([0, 1], [37,11])); ConcMatrix(x3==1) = [NaN]; ConcMatrix(:,6:7) = NaN;
%ConcMatrix = fillmissing(ConcMatrix, 'linear');
% create random dates
NUMBER_RANDOM_TIMES = 37; SECONDS_PER_DAY = 24*60*60;
START_DATE = '2010-01-01'; END_DATE = '2020-01-30';
startDateNum = datenum(START_DATE,'yyyy-mm-dd'); endDateNum = datenum(END_DATE, 'yyyy-mm-dd');
dayRange = endDateNum - startDateNum; secondsRange = SECONDS_PER_DAY*dayRange; randomNumberOfSeconds = randi(secondsRange,NUMBER_RANDOM_TIMES,1);
randomDatenums = startDateNum + randomNumberOfSeconds/SECONDS_PER_DAY;
date= datetime(datestr(randomDatenums));
% Plot
figure
Location = "Location A"; nrGWM = 6; nrVZ = 5; nrRain = 0; nrSites = nrGWM + nrVZ + nrRain;
ConcPlot(date,Location,Chemical,ConcMatrix,nrGWM,nrVZ,nrRain,Colour)
title(sprintf("%s",Location));
% Concentration Plot-Function
function ConcPlot(date,Location,Chemical,ConcMatrix,nrGWM,nrVZ,nrRain,Colour)
nrSites = nrGWM + nrVZ + nrRain;
for i=1:nrSites
if i <= nrGWM
plot(date,ConcMatrix(:,i),'-s','MarkerFaceColor',Colour(i,:),'Color',Colour(i,:))
Legend{i}=sprintf('GWM %1.0f',i);
hold on
elseif (i > nrGWM) && (i <= nrGWM + nrVZ)
plot(date,ConcMatrix(:,i),'-o','MarkerFaceColor',Colour(i-nrGWM,:),'Color',Colour(i-nrGWM,:))
Legend{i}=sprintf('VZ %1.0f',i-nrGWM);
elseif i > (nrGWM+nrVZ)
plot(date,ConcMatrix(:,i),'v','MarkerFaceColor',Colour(i-nrGWM-nrVZ,:)) %,Colour(i,:))
Legend{i}=sprintf('Rain %1.0f',i-nrGWM-nrVZ);
end
end
title(sprintf("%s Concentration in %s",Chemical,Location))
xlabel("Sampling Date");
ylabel(sprintf("%s concentration [mg/L]",Chemical));
legend(Legend);
ylim([0 1])
end
Thank you for your help, Freya
PS: This is what the plot looks like so far. But what I would like to do is connect the dots of same shape & colour in chronological order. I.e. I want to connect all the red(/green/blue/pink) dots with lines and all the red(/green/blue/pink) square with lines. The lines should start at the first appearing symbol (eg. green square at 2012) and then continue to the next symbol of the same type: so green square between 2012 & 2013.
Freyahttps://se.mathworks.com/matlabcentral/profile/authors/4762916-freya