https://uk.mathworks.com/matlabcentral/answers/questionsMATLAB Answers — New Questions2021-03-06T15:03:37Ztag:uk.mathworks.com,2005:Question/7635662021-03-05T05:01:55Z2021-03-06T15:03:28ZHow to set DQN network to approach Q0 ?I'm using the reinforcement learning toolbox to design and train a DQN agent.
My action space is a discrete action space composed by 24 elements. The network is a convolutional neural network inspired by the dueling DQN architecture, these are my convolutional layers:
Layers = [
imageInputLayer([h w 5],"Name","imageinput","Normalization","none")
convolution2dLayer([8 8],64,"Name","conv_1","Padding","same","Stride",[4 4])
reluLayer("Name","relu1")
convolution2dLayer([8 8],64,"Name","conv_1.2","Padding","same")
reluLayer("Name","relu1.2")
convolution2dLayer([4 4],128,"Name","conv_2","Padding","same","Stride",[2 2])
reluLayer("Name","relu2")
convolution2dLayer([4 4],128,"Name","conv_2.2","Padding","same")
reluLayer("Name","relu2.2")
convolution2dLayer([4 4],128,"Name","conv_2.3","Padding","same")
reluLayer("Name","relu2.3")
convolution2dLayer([3 3],256,"Name","conv_3","Padding","same","Stride",[2 2])
reluLayer("Name","relu3")
convolution2dLayer([3 3],256,"Name","conv_3.2","Padding","same")
reluLayer("Name","relu3.2")
convolution2dLayer([3 3],256,"Name","conv_3.3","Padding","same")
reluLayer("Name","relu3.3")];
I'm obtaining bad results during training in the sense that the reward continuously oscillates in the same range of values without improving as if the agent is not learning. Moreover at some point the episode Q0 diverges drastically, I've found on the documentation that: "For agents with a critic, Episode Q0 is the estimate of the discounted long-term reward at the start of each episode, given the initial observation of the environment. As training progresses, if the critic is well designed. Episode Q0 approaches the true discounted long-term reward, as shown in the preceding figure."
Therefore my question is the following : in order to make the Q0 approach the episode reward values how can I modify my network? May be there other problems?
The parameters I'm using for the agent are the following:
criticOpts.Optimizer = 'adam';
criticOpts.LearnRate = 0.00025;
agentOpts.UseDoubleDQN = true;
agentOpts.ExperienceBufferLength = 1e6;
agentOpts.NumStepsToLookAhead = 1;
agentOpts.DiscountFactor = 0.99;
agentOpts.EpsilonGreedyExploration.Epsilon = 1;
agentOpts.EpsilonGreedyExploration.EpsilonMin = 0.1;
agentOpts.EpsilonGreedyExploration.EpsilonDecay = 0.01;
agentOpts.MiniBatchSize = 64;
agentOpts.TargetUpdateMethod = 'smoothing';
agentOpts.TargetUpdateFrequency = 1;
agentOpts.TargetSmoothFactor = 1e-3;Matteo Padovanihttps://uk.mathworks.com/matlabcentral/profile/authors/8146639tag:uk.mathworks.com,2005:Question/7648362021-03-06T15:01:09Z2021-03-06T15:01:09Zhow can I show double data?Hi
I had a data in Nifti format that I converted to double, which turned out to be a double data 423 * 512 * 512. How can this double data be displayed? I do not get the correct result with the imshow command.
thankssara sharifihttps://uk.mathworks.com/matlabcentral/profile/authors/21764780tag:uk.mathworks.com,2005:Question/7646912021-03-06T11:17:10Z2021-03-06T15:03:37ZCreating a table with matrices and arrays as elementsHi, Hope you're safe and fine.
My question is how to create a table whose elements are not necessarily of the same rows. For instance, I have attached a built-in table from "Monocular Visual Odometry" example of MATLAB. In this table, the first element is a number, the second one is a 1x3 vector of location, and the thrid one is a 3x3 matrix of rotation.
Any ideas are appreciated!Mohammad Hussein Yoosefianhttps://uk.mathworks.com/matlabcentral/profile/authors/9905478tag:uk.mathworks.com,2005:Question/7648262021-03-06T14:47:55Z2021-03-06T14:58:30ZAdd to a vector from loopTeam,
Just learning how to use MatLab here,
How do I insert the value n into a different variable so I can recall each number? Any other advice is much appreciated. I just started MATH240 so will need more help later ;)
-----------------------------------------------
totaln=0;
n=1;
for n=1:1000000;
if abs(cos(n))<1/n;
totaln=totaln+1;
display(n) %this displays n but then updates it with the next iteration, I want to insert the value of n into a vector so I can see recall them later.
n=n+1;
else;
n=n+1;
end;
end;Matt Baronhttps://uk.mathworks.com/matlabcentral/profile/authors/12922492tag:uk.mathworks.com,2005:Question/7648162021-03-06T14:39:02Z2021-03-06T14:58:21Zhow to fix ode45 parameters?Error using derivative
Expected state to be finite.
Error in jointSpaceMotionModel/derivative (line 251)
validateattributes(state, {'double'}, {'nonempty', 'vector', 'numel', 2*obj.NumJoints,
'finite', 'real'}, 'derivative', 'state');
Error in file_verifica_controllori>@(t,y)derivative(computedTorqueMotion,y,qDesComputedTorque) (line
31)
[tComputedTorque,yComputedTorque] =
ode45(@(t,y)derivative(computedTorqueMotion,y,qDesComputedTorque),tSpan,initialState);
Error in ode45 (line 299)
f2 = odeFcn_main(t2, y2);
Error in file_verifica_controllori (line 31)
[tComputedTorque,yComputedTorque] =
ode45(@(t,y)derivative(computedTorqueMotion,y,qDesComputedTorque),tSpan,initialState);
Hi! what's the problem with ode45? I tried to reduce the step size but didn't work.Valeria Letohttps://uk.mathworks.com/matlabcentral/profile/authors/10598907tag:uk.mathworks.com,2005:Question/7645312021-03-06T06:48:06Z2021-03-06T14:56:49ZCreate all combination of stringsHello guys,
I need to create a matrix permutation with value from P1:P8. I tried to use the following code:
Pat = sym('p', [1 8]);
pn = nchoosek([Pat],5);
Str = string(pn)
"p1" "p2" "p3" "p4" "p5"
"p1" "p2" "p3" "p4" "p6"
"p1" "p2" "p3" "p5" "p6"
"p1" "p2" "p4" "p5" "p6"
"p1" "p3" "p4" "p5" "p6"
"p2" "p3" "p4" "p5" "p6"
"p1" "p2" "p3" "p4" "p7" ...
The code worked; nevertheles, it gave me only all possible combinations instead of all permutations. Next I tried this following code:
x = sym('p', [1 8]);
K = 5;
C = cell(K, 1);
[C{:}] = ndgrid(x);
y = cellfun(@(x){x(:)}, C);
y = [y{:}];
But the thing is that this code seems a lot for my computer to handle. So would like your help to see if I can generate all permitation of the string P1:P8.
Thank you in advance
Celso Mauro Nhanga Dos Santoshttps://uk.mathworks.com/matlabcentral/profile/authors/19340029tag:uk.mathworks.com,2005:Question/7647812021-03-06T12:51:28Z2021-03-06T14:53:25ZHow can i add data from multiple tables?I have a data set of six tables containing energy production.
They contain 2 rows and different number of columns.
Row 1 contains dates with different starting points, row 2 contains production values.
I have imported 6 tables, and added the range command to align the dates, as they have the same ending point.
They look like this.
V = readtable('Valsneset2006.xlsx','Range','A4:B4783');
S = readtable('Skomakerfjellet2016.xlsx','Range','A4:B4783');
The S matrix has over 3000 empty cells before it lines up with V, but i can't seem to find a better way to aling them.
I want to add the production numbers in row 2 of the different tables to view the total energy production each day.
How can i achieve this?
Thanks in advance!Oscar Rognebyhttps://uk.mathworks.com/matlabcentral/profile/authors/13334956tag:uk.mathworks.com,2005:Question/7647962021-03-06T13:58:17Z2021-03-06T14:52:44ZHow to position and resize the list box window?Hello everyone,
I have the following code:
list = {...
['Start the dataimport (with a total of' num2str(height(Datapoint)) 'datapoints']...
,'rerun the script'...
};
[indx] = listdlg('SelectionMode','single','ListString',list);
if indx == 1
%do some stuff
end
if indx == 2
%rerun script
end
where the variable Datapoint represents the amount of datapoints (245256 x 1) double.
I would like to inform the user about the datapoints that were generated through the script. However the window size looks squeezed and therefore hinders the correct reading of the full sentence. How can I:
a.) Resize the list box window. I am familiar with the Position[0.2 0.2 0.2 0.2] command but I have no idea where to implement it correctly
b.) reposition the window freely, not through the commands left right bottom or top
How could I achieve this desired options?David Mrozekhttps://uk.mathworks.com/matlabcentral/profile/authors/21647186tag:uk.mathworks.com,2005:Question/7647762021-03-06T12:42:02Z2021-03-06T14:50:53ZHow to Vecrorizing conditional vactor mapping problem?Dear,
A is a binary vector its values correspond to the number of times to repeat the
corresponding number drawn from the vector B. 0 value in A means copying value from B to C while 1 value in A means representing the corresponding value in B by 3 bits.
as an example:
A=[0 1 0 0 0 1];
B=[0 1 0 1 0 0];
C=[0 0 0 1 0 1 0 0 0 0]
Can we avoid using classical loop?
RegardsOmar Ali Muhammedhttps://uk.mathworks.com/matlabcentral/profile/authors/17769638tag:uk.mathworks.com,2005:Question/7648312021-03-06T14:50:45Z2021-03-06T14:50:45ZHow to vary a variable in a system of ODE's?Hello everybody,
I want to make a plot where I from where I can find and show the best value for a parameter. In order to do this I have to vary a variable in my system of ODE's (here a simplified example from the Matlab site). In the lines of codes below I show the set of ODE's, here Tau is the variable that I want to vary. In other words, I want solutions for a system where Tau = 1, Tau = 2, Tau = 3, etc. I tried to do this using a for-loop but it doesn't seems to be working as only the first two columns are calculated and the last ones remain their inital values. Does somebody have a smart solution?
function dpdt = Tester(t,p,val)
dpdt = zeros(2*val,1);
delta = 0.02;
beta = 0.01;
for tau = 1:1:val
dpdt(1) = val * p(1) .* (1 - beta*p(2));
dpdt(2) = val * p(2) .* (-1 + delta*p(1));
end
end
And the solution script is given below:
tspan = [0 15]
val = 2;
[t,p] = ode45(@Tester,tspan,[5 5 50 50],[],val);
plot(t,p)
title('Predator/Prey Populations Over Time')
xlabel('t')
ylabel('Population')
legend('Prey','Predators')
Thanks in advance for your help. Danny Helwegenhttps://uk.mathworks.com/matlabcentral/profile/authors/14114779tag:uk.mathworks.com,2005:Question/7648212021-03-06T14:46:39Z2021-03-06T14:50:25ZHi, I am new to matlab. Please can anyone tell me how can I read multiple image subfolders and display a fixed amount of images randomly?I don't have any code for it at the moment.jennie jameshttps://uk.mathworks.com/matlabcentral/profile/authors/21764683tag:uk.mathworks.com,2005:Question/7647862021-03-06T13:09:55Z2021-03-06T14:47:56Zhow to scan the element of a matrixgiven a 12 by 12 matrix, how can i use the for loop and if statement to find a specific element.Sean Achonghttps://uk.mathworks.com/matlabcentral/profile/authors/21747020tag:uk.mathworks.com,2005:Question/1337892014-06-11T18:46:46Z2021-03-06T14:47:22ZHow can I plot the same data with two y-axes on the same plot?I have some error analysis that requires looking at absolute as well as percent error of some data. I toyed around with plotyy but it essentially plots the data twice with each y-axis. Anyone know how to plot the data once with one scale on the left y-axis (absolute error) and another scale on the right (percent error)
Thanks!Andreahttps://uk.mathworks.com/matlabcentral/profile/authors/3089007tag:uk.mathworks.com,2005:Question/7642212021-03-05T18:41:16Z2021-03-06T14:43:36ZHow can I record mouse clicks (left and right) with coordinates and time? Hello,
I am trying to capture mouse movements outside of the GUI, on second display while users are using another program. So far, I manage to record the coordinates, every 0.1 seconds period, by using timer function. I need to add mouse clicks (left or right button down and ups). Does anyone know how can I do this? I try to Buttondownfnc but it only works with a figures not outside of the Matlab..or is there any workaround?
fileID = fopen('motion.txt','wt');
t = timer('ExecutionMode', 'fixedRate','Period', 0.1, 'TasksToExecute', 200, ...
'TimerFcn', @(~,~) fprintf(fileID,'(X, Y) = (%g, %g)\n', get(0, 'PointerLocation')));
start(t);Doli Sweyhttps://uk.mathworks.com/matlabcentral/profile/authors/19536320tag:uk.mathworks.com,2005:Question/5537442020-06-24T05:29:42Z2021-03-06T14:43:33Zcalculate SPL-Third octave using poctave functionI want to calculate the sound pressure level third ooctave using poctave function
I used poctave function to convert pressure data (p) (time,pressure) to 1/3 octave spectrum
[P3rd, cf] = poctave(p,fs,'FrequencyLimits',[df,fs/2],'BandsPerOctave',3);
In order to calculate the SPL-1/3 Octave (sploct)
sploct = 10*log10(P3rd/pref^2);
Is the equation for calculating SPL-1/3 octave is correct or not?zeinhttps://uk.mathworks.com/matlabcentral/profile/authors/17514856tag:uk.mathworks.com,2005:Question/5166042020-04-09T12:11:25Z2021-03-06T14:38:36Z6 equation with 6 unknownsHello everyone ,
I have 6 equations with 6 unknowns and ı dont know how to implement in matlab .Could you please help me ?
967.85 = L+V
611.6812=L*x(1) + V*y(1)
265.1909=L*x(2) +V*y(2)
x(1)*256.98=y(1)*1350.49
x(2)*1350.49=y(2)*556.29
(1-x(1)-x(2))*556.29=(1-y(1)-y(2))*256.98
Unknowns ; L ,V,x(1),x(2),y(1),y(2)enis çokohttps://uk.mathworks.com/matlabcentral/profile/authors/18109325tag:uk.mathworks.com,2005:Question/7559192021-02-25T12:47:43Z2021-03-06T14:32:26Zhow to plot contour lines on Joint Histogram plot Hi all,
I am plotting joint histogram by using histogram2 as shown in figure.
I need contour lines to differentiate each color which gives clear picture of data distribution means lines to separate each color .
Can anyone help me with this?
my code for this plot as follows:
clf
figure(1)
Yedges = [0.25:.25:100];
Xedges = [50:2.5:350];
h= histogram2(olr,rf,Xedges,Yedges,'DisplayStyle','tile','FaceColor','flat')%,'Normalization','pdf')
colorbar;
colormap(hsv(15))
ylim([0 100])
ax=gca;
ax.CLim=[0 100]
And, The kind of figure I want should look like(plotted in Rstudio):
Thanks,
UtkarshUTKARSH VERMAhttps://uk.mathworks.com/matlabcentral/profile/authors/9683896tag:uk.mathworks.com,2005:Question/7648012021-03-06T13:59:25Z2021-03-06T14:24:25ZProblem using ODE45 - current not recognizedI am using this function:
%Constants set
Cm=0.01; % Membrane Capcitance
dt=0.01; % Time Step ms
t=0:dt:25; %Time Array ms
I = zeros (145,1); %Applied constant
I(40:50,1) = 0.1; %Applied constant
V=-60; % Initial Membrane voltage
m=alpham(V)/(alpham(V)+betam(V)); % Initial m-value
n=alphan(V)/(alphan(V)+betan(V)); % Initial n-value
h=alphah(V)/(alphah(V)+betah(V)); % Initial h-value
y0=[V;n;m;h];
tspan = [0,max(t)];
%Matlab's ode45 function
[time,V] = ode45(@ODEMAT,tspan,y0);
OD=V(:,1);
ODn=V(:,2);
ODm=V(:,3);
ODh=V(:,4);
%% Plots
figure
subplot(3,1,1)
plot(time,OD);
legend('ODE45 solver');
xlabel('Time (ms)');
ylabel('Voltage (mV)');
title('Voltage Change for Hodgkin-Huxley Model');
subplot(3,1,2)
plot(time,I);
legend('Current injected')
xlabel('Time (ms)')
ylabel('Ampere')
title('Current')
subplot(3,1,3)
plot(time,[ODn,ODm,ODh]);
legend('ODn','ODm','ODh');
xlabel('Time (ms)')
ylabel('Value')
title('Gating variables')
With ODEMAT being:
function [dydt,I] = ODEMAT(t,y)
%Constants
ENa=55.17; % mv Na reversal potential
EK=-72.14; % mv K reversal potential
El=-49.42; % mv Leakage reversal potential
gbarNa=1.2; % mS/cm^2 Na conductance
gbarK=0.36; % mS/cm^2 K conductance
gbarl=0.003; % mS/cm^2 Leakage conductance
I = zeros (145,1); %Applied constant
I(40:50,1) = 0.1; %Applied constant
Cm = 0.01; % Capacitance
% Values set to equal input values
V = y(1);
n = y(2);
m = y(3);
h = y(4);
gNa = gbarNa*m^3*h;
gK = gbarK*n^4;
gL = gbarl;
INa=gNa*(V-ENa);
IK=gK*(V-EK);
Il=gL*(V-El);
for curr = 1:length(I)
dydt = [((1/Cm)*(I(curr)-(INa+IK+Il))); % This is voltage
alphan(V)*(1-n)-betan(V)*n; %This is gating conductance A
alpham(V)*(1-m)-betam(V)*m; %This is gating conductance B
alphah(V)*(1-h)-betah(V)*h]; %This is gating conductance C
end
end
So what I'm trying to do here is see what happens to voltage and gating conductances when current I switched from 0 to 0.1 (at timestep 40 until 50). However, it looks like the function doesn't really take 0.1 as input, and keeps using 0 instead. Where am I getting it wrong? I also attach the six alpha and beta functions.
Thanks,
SamueleSamuele Bolottahttps://uk.mathworks.com/matlabcentral/profile/authors/16756884tag:uk.mathworks.com,2005:Question/5037022020-02-05T02:14:52Z2021-03-06T14:17:21ZPlot same data set on two different y axis scales NOTE: Question has been updated.
Hello all,
I want to plot a matrix (37 x 10) represented by sum_ET10 with 2 different y axis scales; km^3/year (original unit) on y axis lhs & mm/year (new unit) on y axis rhs. My code is shown below; I have also included an image below. Currently, my graph is still incorrect. What I want to do is to have a single plot as opposed to the two plots that I'm getting
%% Getting a 37 x 10 matrix of sum_ET10 & sum_area
decade = 10;
sum_area = squeeze(sum(reshape(area,size(area,1),decade,[]),2)/10);
sum_ET10 = squeeze(sum(reshape(ET,size(ET,1),decade,[]),2)/10);
% Plot the results
x_decade = 1:10;
f1 = figure(1);
x1 = axes;
plot(x_decade,sum_ET10(1,:),'-ok');
% Query the YTicks
yt = get(x1,'YTick');
% Create new axis based on existing axis
x2 = copyobj(x1,f1);
% Set new axis transparent
set(x2,'Color','none')
% Remove XTicks
set(x2,'Xtick',[])
% Display the YTicks on the right side
set(x2,'YAxisLocation','right')
% Converting values to mm/year
mm_sum_ET10 = yt/2199000*1000000;
% Update labels
set(x2,'YTickLabel',mm_sum_ET10)
grid on;
xlabel(x1,'Decade');
ylabel(x1,'km^3/year');
ylabel(x1,'mm/year');
Any help is appreciated. This is my first time doing different scaled axes, so I'm in need of help.
Thank you.Elizabeth Yeaphttps://uk.mathworks.com/matlabcentral/profile/authors/8460975tag:uk.mathworks.com,2005:Question/7648062021-03-06T14:14:50Z2021-03-06T14:14:50ZA MATLAB Dice Function to display the face of the dicePlease help me with this question, it is related to plotting :
Write a MATLAB function called ‘dice’. The function should open a figure and display the given face of a regular six-sided die. The face ‘number’ is the only input argument, k. Examples of the desired output are shown in Figure. Notice the rounded corners. The orientation of faces 2, 3 and 6 does not matter as long as the white dots form the desired pattern.
Anand Sonihttps://uk.mathworks.com/matlabcentral/profile/authors/21576733tag:uk.mathworks.com,2005:Question/7647112021-03-06T11:26:01Z2021-03-06T14:09:36ZIsolate clusters from a series of pointsI have a set of points whose x and y coordinates are stored into two vectors (Lpix_x and L_pix_y, each composed of 3067 elements).
imshow(Imm)
hold on
plot(Lpix_x,Lpix_y,'go')
Plotting the vector on a image I obtain this result
I want to plot only the clusters of points circled in red, deleting the other points.
I thought about computing the euclidean distance between each point and its subsequent and then saying that 'if distance is > than a certain threshold, then the corresponding elements in Lpix_x and L_pix_y must be deleted'.
n = 3067;
for i = 1:n-1
Xdist(i) = Lpix_x(i+1) - Lpix_x(i);
Ydist(i) = Lpix_y(i+1) - Lpix_y(i);
dist(i) = sqrt((Xdist(i))^2 + (Ydist(i))^2);
if dist(i)>2 % 2 is an example of threshold
%???????
end
end
I don't know what to put instead of ???? . What should I say there?
If there is another way to solve the problem, any suggestion will be well accepted.
Thank you Federicahttps://uk.mathworks.com/matlabcentral/profile/authors/11007789tag:uk.mathworks.com,2005:Question/7646662021-03-06T10:59:07Z2021-03-06T14:08:42ZGenerate cell of random numbers with same size arraysHello!
I'd like to generate a 3x2 cell, whose arrays are all matrices 5x100 of random numbers.
I am a bit struggling with it, despite I think is quite easy to do.
Any suggestion?
ThanksRiccardo Zabattahttps://uk.mathworks.com/matlabcentral/profile/authors/16761799tag:uk.mathworks.com,2005:Question/7641162021-03-05T16:58:31Z2021-03-06T14:07:41Zintersection area of 3 or more rectangleshi all, I have multiple rectangles defined by rectangle()- function. I now want to find the intersection area of 3 rectangles (I know that for 2 rectangles rectint works). Alternatively it might be an option to find the intersection area of the intersection (rectangle 1, rectangle 2) with the rectangle 3.
Is there a funtion or simple solution for this problem?
Thanks!Tobias Eißlerhttps://uk.mathworks.com/matlabcentral/profile/authors/20197877tag:uk.mathworks.com,2005:Question/7548842021-02-24T14:03:26Z2021-03-06T14:03:43ZProblem compiling with Intel C compiler via MATLAB CoderI have registered a toolchain that uses the Intel C compiler (icc), but compilation fails because icc does not recognize NAN and INFINITY in the file rt_nonfinite.c. The problematic lines are
real_T rtNaN = (real_T)NAN;
and
real_T rtInf = (real_T)INFINITY;
I thought I had solution when I added
tc.addMacro('C_STANDARD_OPTS',' -D__PURE_INTEL_C99_HEADERS__ ');
to my m-file defining the toolchain object. But now compilation fails due to the same lines (and more) in rt_nonfinite.c, but for a different reas on. The error is now
error: expression must have a constant value.
I know that NAN and INFINITE are defined in the math.h that comes with icc. Could icc be unaware of its own header files? How can I fix that?
Thanks in advance for advice and insight. I am working on a 64 bit Linux box.Joe Mhttps://uk.mathworks.com/matlabcentral/profile/authors/20296699tag:uk.mathworks.com,2005:Question/4940512019-11-30T18:20:08Z2021-03-06T13:48:51ZHow to control a Revolute Joint using PID in a manupilator ?I have imported a CAD model from PTC Creo and I want to control the joints using PID controller. I need a circuit to control the joint. Any help is appreciated.
PFATasneem Khanhttps://uk.mathworks.com/matlabcentral/profile/authors/16668574tag:uk.mathworks.com,2005:Question/7585192021-02-28T12:40:20Z2021-03-06T13:46:45ZdetectCheckerboardPoints function is not able to detect the corner points of the boardI am using MATLAB R2020b to calibrate a camera for an experiment. I have 2 images my checkerboard at a required angle. i cannot perform the calibration, because detectCheckerboardPoints function is not able to detect the corner points of the board. I used the same board in a different angle, in former setup of the experiment and the function worked fine.
this is the code i use:
figure (1)
f = 'calib2 34stage_hor_4l_roll-29pitch_-260 rail_gain20_64Hz_end_board_2603_mm.tiff';
[imagePoints,boardSize,imagesUsed] = detectCheckerboardPoints(f);
I = imread(f);
imshow(I);
hold on
M = prod(boardSize-1);
plot(imagePoints(:,1),imagePoints(:,2),'.r','MarkerSize',8);
hold on
for i = 1:length(imagePoints(:,1))
t = text(imagePoints(i,1),imagePoints(i,2),num2str(i),'FontSize',8);
t.Color = [1 0 0];
end
title ('checkerboard light on calibration points')
This is the error message:
Index in position 2 exceeds array bounds.
Error in transformation2 (line 12)
plot(imagePoints(:,1),imagePoints(:,2),'.r','MarkerSize',8);
I am attaching the image for refference (I am using tiff format, but it cannot be uploae here so JPG is attache). I would appreciate guidance on how to solve this matter
Noam noam giniohttps://uk.mathworks.com/matlabcentral/profile/authors/12591825tag:uk.mathworks.com,2005:Question/4613262019-05-10T11:04:41Z2021-03-06T13:44:29Zlots of errors in the matlab prompt on ubuntuive installed matlab 2018b on my ubuntu
the matlab works but the prompt is keep getting the following prints which makes it impossible to work with the program
Cookie: JSESSIONID2=2Iiv2CZq40cSa3qW; ssnc=WJYS3uMFWTvuh5C7
, overrideHeaders=}, SocketInfo{channelId=0, browserId=-1, channelType=Main}
01:59:40 INFO: WRITE: OnBeforeSendHeadersMessage{type=OnBeforeSendHeaders, uid=791, browserContextId=0, requestId=82, url=https://localhost:31516/messageservice/async, method=POST, originalHeaders=Origin: https://localhost:31516
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.52 Safari/537.36
Content-Type: application/json
Accept: */*
Referer: https://localhost:31516/remote/proxy/1.5/iframeProxyRelease.html
Accept-Encoding: gzip, deflate
Accept-Language: en-il
Cookie: JSESSIONID2=2Iiv2CZq40cSa3qW; ssnc=WJYS3uMFWTvuh5C7
, overrideHeaders=}, SocketInfo{channelId=0, browserId=-1, channelType=Main}
01:59:41 INFO: READ: OnSendHeadersMessage{type=OnSendHeaders, uid=792, browserContextId=0, requestId=82, url=https://localhost:31516/messageservice/async, method=POST, headers=Origin: https://localhost:31516
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.52 Safari/537.36
Content-Type: application/json
Accept: */*
Referer: https://localhost:31516/remote/proxy/1.5/iframeProxyRelease.html
Accept-Encoding: gzip, deflate
Accept-Language: en-il
Cookie: JSESSIONID2=2Iiv2CZq40cSa3qW; ssnc=WJYS3uMFWTvuh5C7
}, SocketInfo{channelId=0, browserId=-1, channelType=Main}
and it keeps on and on
ive tried fixing it but with no luck
would appricate some help
Thanksdavid srikerhttps://uk.mathworks.com/matlabcentral/profile/authors/12301123tag:uk.mathworks.com,2005:Question/7647262021-03-06T11:36:44Z2021-03-06T13:43:43ZHow to find intersection between lines I have below code
%% Input Values
clear all
clc
alpha1=input('Enter positive "alpha1"?');
alpha2=input('Enter positive "alpha2"?');
beta1=input('Enter positive "beta1"?');
beta2=input('Enter positive "beta2"?');
lambda=input('Enter positive "lambda"?');
eta1=input('Enter positive "eta1"?');
eta2=input('Enter positive "eta2"?');
P=input('Enter positive "P"?');
%% Feasible Area
x = -1:P;m = 0; c = eta2; y = m * x + c;
plot(x, y, 'black')
y = -1:P; m = 0; c = eta1; y = m * x + c;
plot(y, x, 'black')
eta1=min (eta1,P); eta2=min (eta2,P);
if eta1==0 && eta2==0;
X=[0 0 P]; Y=[0 P 0];
fill(X,Y,[0.85 0.85 0.85]); axis([-1 P -1 P])
end
if eta1+eta2<P
X=[0 0 eta1 eta1]; Y=[0 eta2 eta2 0];
fill(X,Y,[0.85 0.85 0.85]);
else
X=[0 0 P-eta2 eta1 eta1]; Y=[0 eta2 eta2 P-eta1 0];
fill(X,Y,[0.85 0.85 0.85]); axis([-1 P -1 P])
end
X=[0 0]; Y=[0 P];
line(X,Y,'Color','black')
hold on
line(Y,X,'Color','black')
g = @(x,y) x+y-P;
y1=fimplicit(g,[0 P 0 P])
f = @(x,y) log((1+alpha1*x./(1+alpha2*y))) -lambda*log((1+beta1*x./(1+beta2*y)));
y2=fimplicit(f,[-1 P -1 P], '-')
hold on
grid on
Where I consider alpha1=1, alpha2=0.2, beta1=1; beta2=2, lambda=2, eta1=2, eta2=3, P=1
I want to find the intersection for lines in the picture. Could you please help me!
Hossein Alishahihttps://uk.mathworks.com/matlabcentral/profile/authors/12960900tag:uk.mathworks.com,2005:Question/7636012021-03-05T06:34:27Z2021-03-06T13:42:12ZCan anybody help me to implement caughey's equivalent linearization method for bilinear structure in MATLAB? I am not able to get the ductility(x/x0) vs frequency ratio(w/ws) plot.These are some images from "Passive control of bilinear hysteretic structures by tuned mass damper
for narrow band seismic motions" Z. Zhang, T. Balendra.
VAIBHAV PUJARIhttps://uk.mathworks.com/matlabcentral/profile/authors/17179308tag:uk.mathworks.com,2005:Question/7625662021-03-04T08:49:32Z2021-03-06T13:36:14ZHow to deal with nested arrays where the columns and rows are in different dimensions?Hello everyone,
In some previous questions I have asked about defining a specific data structure which gave me splendid answers and a better understanding of organizing those data. Now, for a deeper meaning I would like to know the following:
I have a (72x1 cell) which content is defined by the following block/section:
COLUMN1
ROW1 Text Nr.1
ROW2 2345x3 double
ROW3 Text Nr.2
....times 24 to get the mentioned 72x1 cell array
My goal now is to unnest the 2345x3 double contents in a way, that I obtain the following data order:
COLUMN1 COLUMN2 COLUMN3
Text Nr.1 (empty) (empty)
value 1 value 1 value 1
value 2 value 2 value 2
value 3 value 3 value 3
value 4 value 4 value 4
value 5 value 5 value 5
value 6 value 6 value 6
value 7 value 7 value 7
etc. etc. etc.
Text Nr.2 (empty) (empty)
Text Nr.1 (empty) (empty)
value 1 value 1 value 1
value 2 value 2 value 2
value 3 value 3 value 3
value 4 value 4 value 4
value 5 value 5 value 5
value 6 value 6 value 6
value 7 value 7 value 7
etc. etc. etc.
Text Nr.2 (empty) (empty)
However this requires me to know about the new shifted positons without overwriting any data:
I tried to write a code with a (for loop?) but I am even unsure how to start nor to implement my thought process in a proper solution.
Hence I would like to know a method which allows me to unnest the above mentioned example into a cell array (N x 1) where N of course is the expanded version of the old nested cell array.
Stay safe and healthy,
David
Additional Notes:
For anyone asking about my intenton behind this question: I succesfully printed some parts in 3D printer yesterday using some of your answers by exporting those into different gcode converters which require different data structures depending on the current used software. In my upcoming research I would like to establish a readable communication path between some gcode readers and 3d printers. Therefore I have already adjusted my code for exporting finished data files as well as textboxes for inputing new data. The only struggle that I am currently dealing is the fact, that I am not familiar with the matlab cell editing operations which lead me to your much more refined approach regarding this matter. David Mrozekhttps://uk.mathworks.com/matlabcentral/profile/authors/21647186tag:uk.mathworks.com,2005:Question/7633912021-03-04T23:23:36Z2021-03-06T13:33:00ZHow to create 3d figures as followsI can lively modify my 3d plots on plots editor, but I want to modify on Editor by codes.
Suppose that we have two figures p1 and p2 as follows:
close all;
clc;
clear all;
[X,Y] = meshgrid(-5:.5:5);
Z = Y.*sin(X) - X.*cos(Y);
p1 = surf(X,Y,Z);
hold on
p2 = surf(X,Y,Z);
I want to achive followings:
-p1 should be red sphere and markersize=12.
-p2 should be turquoise color and linestyle=none.
-axes gridlinestyle should be '-.' and axes gridline color=blue.
-Can legends be placed in a specific coordinate like (x=2,y=5,z=8)?
Consequently, I want to get a figure similar to the following:
student_mdhttps://uk.mathworks.com/matlabcentral/profile/authors/9297723tag:uk.mathworks.com,2005:Question/7646862021-03-06T11:13:20Z2021-03-06T13:30:17Znum2str formatI have problems with num2str format
I get a number from an API:
8.1784e+17
I need the exact number as str output. For instance I know it is:
'817835078876192769'.
I tried with:
num2str(x,'%u')
however this gives me the following wrong result:
ans =
'817835078876192768'
Anyone have a clue what can be wrong here?Martinhttps://uk.mathworks.com/matlabcentral/profile/authors/4265483tag:uk.mathworks.com,2005:Question/7645862021-03-06T08:39:17Z2021-03-06T13:28:25ZHow Can speed up "for" loop ?Hi,
How can I speed up following 'for' loops? Help me please.Thanks.
N=1000 > 30sec , N=1000 > 10min , N=100000 > 5hr up can't produce result
N = 100000;
B= 0.3;
Pf=linspace(0.9,0.1,n);
data = randi([0,1],N, 1);
for k=1:2
Lambda= (1+sqrt(2/N)*qfuncinv(Pf))*var(wgn(N, 1,0) .* sqrt(p(k)/2));
for i = 1:length(Pf)
Nd_BPSK=0;
for j=1:N
noise_BPSK = wgn(N, 1,0) .* sqrt(p(k)/2);
h_BPSK = raylrnd(B, N, 1);
receive_BPSK = abs(h_BPSK).*send_BPSK + noise_BPSK;
T_simu_BPSK(i)=sum(abs(receive_BPSK).^2)/N;
if T_simu_BPSK(i) > Lambda(i)
Nd_BPSK=Nd_BPSK+1;
end
end
Pd_simu_BPSK(i,k)=Nd_BPSK/j;
end
for i = 1:length(Pf)
Nd_QPSK=0;
for j=1:N
noise_QPSK = wgn(N/2, 2, 0) .* sqrt(p(k)/2);
h_QPSK = raylrnd(B, N/2, 2);
receive_QPSK = abs(h_QPSK).*send_QPSK + noise_QPSK;
receive_QPSK2=reshape(receive_QPSK,N,1);
T_simu_QPSK(i)=sum(abs(receive_QPSK2).^2)/N;
if T_simu_QPSK(i) > Lambda(i)
Nd_QPSK=Nd_QPSK+1;
end
end
Pd_simu_QPSK(i,k)=Nd_QPSK/j;
end
endNYYminhttps://uk.mathworks.com/matlabcentral/profile/authors/17813948tag:uk.mathworks.com,2005:Question/3958952018-04-18T19:44:13Z2021-03-06T13:26:39ZHow can I get a loop to process all ".avi" files in a folder, then produce the corresponding ".txt" and ".png" file?I am creating a deep learning CNN with Python and Tensorflow, but the information that will be used in the network will be processed in MATLAB, and so my task is as follows:
I am to use MathWorks' sample code for MotionBasedMultiObjectTracking, but modify it in such a way that as it tracks a moving object, such as a person, in a supplied '.avi' file, it retrieves the (x,y) coordinates of the centroid of the bounding box as it moves in each frame, and writes that information to a '.txt' file. While it does this, it should also print a pattern of white dots onto an all black image, which represents the centroid/(x,y) coordinates as they change across each frame, and save the resulting image as a '.png' file.
I already have this part but that information was supplied just to provide a better understanding of what I'm trying to accomplish overall. Now my problem is that I can't figure out how to write a function or script that can go through all of my .avi files and produce the corresponding x,y coord .txt file and dot pattern .png file. Here is some code:
function MotionBasedMultiObjectTrackingExample()
% create a white image
imageTraj = 255 * ones(480, 640, 'uint8');
blackTraj = 0 * imageTraj;
% create a file to save trajectory data
fileID = fopen('Pattern 1-1.txt','w+');
%imshow(image);
% Create System objects used for reading video, detecting moving objects,
% and displaying the results.
obj = setupSystemObjects();
tracks = initializeTracks(); % Create an empty array of tracks.
nextId = 1; % ID of the next track
% Detect moving objects, and track them across video frames.
while ~isDone(obj.reader)
frame = readFrame();
[centroids, bboxes, mask] = detectObjects(frame);
predictNewLocationsOfTracks();
[assignments, unassignedTracks, unassignedDetections] = ...
detectionToTrackAssignment();
updateAssignedTracks();
updateUnassignedTracks();
deleteLostTracks();
createNewTracks();
displayTrackingResults();
end % end of while
fclose(fileID);
saveas(gcf,'Pattern 1-1.png');
%open the generated image for dilation
BW = imread('Pattern 1-1.png')
%dilation function(strel('dilation type', dilation_strength))
SE = strel('square', 8);
%actually perform the dilation and show the new dilation image
BW2 = imdilate(BW,SE);
figure,imshow(BW2), title('Dilated')
%resize the dilated image
BW3 = imresize(BW2, [64 64]);
figure, imshow(BW3), title('Resized and dilated')
saveas(BW3,'resizedBW3.png');
%% Create System Objects
% Create System objects used for reading the video frames, detecting
% foreground objects, and displaying results.
function obj = setupSystemObjects()
% Initialize Video I/O
% Create objects for reading a video from a file, drawing the tracked
% objects in each frame, and playing the video.
% Create a video file reader.
%obj.reader = vision.VideoFileReader('udcvideo.mp4.mp4');
obj.reader = vision.VideoFileReader('Scenario 1-1.avi');
% Create two video players, one to display the video,
% and one to display the foreground mask.
obj.maskPlayer = vision.VideoPlayer('Position', [740, 400, 700, 400]);
obj.videoPlayer = vision.VideoPlayer('Position', [20, 400, 700, 400]);
% Create System objects for foreground detection and blob analysis
% The foreground detector is used to segment moving objects from
% the background. It outputs a binary mask, where the pixel value
% of 1 corresponds to the foreground and the value of 0 corresponds
% to the background.
obj.detector = vision.ForegroundDetector('NumGaussians', 3, ...
'NumTrainingFrames', 40, 'MinimumBackgroundRatio', 0.7);
% Connected groups of foreground pixels are likely to correspond to moving
% objects. The blob analysis System object is used to find such groups
% (called 'blobs' or 'connected components'), and compute their
% characteristics, such as area, centroid, and the bounding box.
obj.blobAnalyser = vision.BlobAnalysis('BoundingBoxOutputPort', true, ...
'AreaOutputPort', true, 'CentroidOutputPort', true, ...
'MinimumBlobArea', 400);
end % end of setupSystemObjects()
My videos are named in the folder as follows: Scenario 1-1 to 1-10, Scenario 2-1 to 2-10.... Scenario 10-1 to 10-10. So there's 100 '.avi' files in the folder. In the setupSystemObjects() function, I supply the video file reader with 'Scenario 1-1.avi'. When I run the program, it runs the process on Scenario 1-1.avi, produces Pattern 1-1.txt, and Pattern 1-1.png, just like I want. The big question is how can I loop it, updating the file name each time so that every time the function is called, it will move to the next file, let's say 'Scenario 1-2.avi' for example, and produce the respective .txt and .png files, all the way until it has finished with the 100 videos in the folder.
I have developed this loop but I'm not sure how to proceed from here: (The comments on the inside below 'code would go here' was just me trying different things.
function FileExample()
d = uigetdir('','Select Input-folder'); %select the input-folder that contains the subfolders
cd(d);
list = dir;
list = list([list.isdir]);
list = list(~ismember({list.name},{'.' '..'}));
l=length(list);
for i=1:l
oldfolder = cd(list(i).name);
% Perform your operation on the files, e.g., if you are working with avi files
files = dir('*.avi');
numberOfFiles = length(files);
for k = 1:numberOfFiles
% code would go here
%
% file name files(k)
% MotionBasedMultiObjectTrackingExample( files(k) )
end
cd(oldfolder);
end
endTevin Galeshttps://uk.mathworks.com/matlabcentral/profile/authors/12419132tag:uk.mathworks.com,2005:Question/698052013-04-04T07:34:30Z2021-03-06T13:25:22ZHow can I train ANFIS using Firefly AlgorithmGood afternoon everyone,
For training ANFIS with Matlab fuzzy logic toolbox, we can either choose backprpagation or Hybrid method as given here http://www.mathworks.com/help/toolbox/fuzzy/anfis.html under 'optMethod'.
But I want to train my ANFIS with Firefly Algorithm (FA) method. And I'm not able to figure out how I can implement my FA algorithm as a training method in ANFIS as I can't find if there is anyway to customize anfis training.
Please help me on how can I train my anfis with my FA method.
Thank you for your help !Nhu Hienhttps://uk.mathworks.com/matlabcentral/profile/authors/4205276tag:uk.mathworks.com,2005:Question/3033912016-09-17T07:27:51Z2021-03-06T13:22:47ZState derivatives returned by S-function during flag=1 call must be a real vectorHello,
I'm working with a simulation model using the input-output feedback linearization controller. And first I got an error saying "Algebraic state in algebraic loop containing 'feedbacklinearization_test2/dynamics' computed at time 0.0 is Inf or NaN. There may be a singularity in the solution. If the model is correct, try reducing the step size (either by reducing the fixed step size or by tightening the error tolerances)".
I've tried to reduce the step size and it didn't work. So I'm trying to use a delay block to avoid the algebraic loop. Here comes a new error saying "State derivatives returned by S-function 'UAV_dynamics' in 'feedbacklinearization_test2/dynamics' during flag=1 call must be a real vector of length 14" .
I have no idea how to solve this problem. Is there anyone who has used this control method or knows how to solve this kind of errors? It's quite urgent. Any useful comments will be appreciated.
BAIHUI DUhttps://uk.mathworks.com/matlabcentral/profile/authors/8762676tag:uk.mathworks.com,2005:Question/7632312021-03-04T19:50:36Z2021-03-06T13:18:45ZHow I plot this ?Please help me to plot this equation
Thanks in advance
log((1+alpha1*x/(1+alpha2*y))) -gamma*log((1+beta1*x/(1+beta2*y)));
alpha1=0.1; alpha2=0.2; beta1=0.2; beta2=1; gamma=1.3;Hossein Alishahihttps://uk.mathworks.com/matlabcentral/profile/authors/12960900tag:uk.mathworks.com,2005:Question/7160282021-01-13T16:35:33Z2021-03-06T13:17:33Zpolyspace-report-generator: an error occurred while parsing class rptgen.DAObjectProblem is reporoducing on Polyspace Bug Finder R2020b,
OS: Ubuntu 16.04 or 18.04.
polyspace-report-generator -format PDF -results-dir results -template /usr/local/Polyspace/R2019a/toolbox/polyspace/psrptgen/templates/bug_finder/BugFinder.rpt
Location: null, user name: andrew, id: 16608@polyspace, print mode: false
Polyspace Report Generator
Loading results
Loaded "polyspace - results"
Generating Report
Template : /usr/local/Polyspace/R2019a/toolbox/polyspace/psrptgen/templates/bug_finder/BugFinder.rpt
Results-dir : /home/andrew/results
Format : dom-pdf-direct
Output-Name : results/Polyspace-Doc/polyspace_BugFinder.pdf
Loading report template
Warning: an error occurred while parsing class rptgen.DAObject:
> In rptgen.rptcomponent/schema
In rptgen.rpt_section/schema
In rptgen.coutline/schema
In RptgenML.CReport/schema
In rptgen/loadRpt
In polyspace_report_internal (line 290)
In psrptgenprivate (line 19)
In polyspace_report (line 7)
Warning: an error occurred while parsing class rptgen.rptcomponent:
Invalid superclass handle.
> In rptgen.rpt_section/schema
In rptgen.coutline/schema
In RptgenML.CReport/schema
In rptgen/loadRpt
In polyspace_report_internal (line 290)
In psrptgenprivate (line 19)
In polyspace_report (line 7)
Warning: an error occurred while parsing class rptgen.rpt_section:
Invalid superclass handle.
> In rptgen.coutline/schema
In RptgenML.CReport/schema
In rptgen/loadRpt
In polyspace_report_internal (line 290)
In psrptgenprivate (line 19)
In polyspace_report (line 7)
Warning: an error occurred while parsing class rptgen.coutline:
Invalid superclass handle.
> In RptgenML.CReport/schema
In rptgen/loadRpt
In polyspace_report_internal (line 290)
In psrptgenprivate (line 19)
In polyspace_report (line 7)
Warning: an error occurred while parsing class RptgenML.CReport:
Invalid superclass handle.
> In rptgen/loadRpt
In polyspace_report_internal (line 290)
In psrptgenprivate (line 19)
In polyspace_report (line 7)
Warning: Variable 'rptgen_component_v2' originally saved as a RptgenML.CReport cannot be instantiated as an object and will be read in as a cell.
> In rptgen/loadRpt
In polyspace_report_internal (line 290)
In psrptgenprivate (line 19)
In polyspace_report (line 7)
Dot indexing is not supported for variables of this type.
Error in rptgen/loadRpt
Error in polyspace_report_internal (line 290)
Error in psrptgenprivate (line 19)
Error in polyspace_report (line 7)
ERROR: Loading report template: /usr/local/Polyspace/R2019a/toolbox/polyspace/psrptgen/templates/bug_finder/BugFinder.rpt
Check if the file is a valid report (.rpt) template.
For more information, enter polyspace-report-generator -h.
Warning: an error occurred while parsing class rptgen.DAObject:
> In polyspace_report_internal/rptgen_unlock (line 942)
In polyspace_report_internal (line 384)
In psrptgenprivate (line 19)
In polyspace_report (line 7)Andrew Kornilovhttps://uk.mathworks.com/matlabcentral/profile/authors/18312345tag:uk.mathworks.com,2005:Question/7646562021-03-06T10:24:52Z2021-03-06T13:15:50Zdeblurring an image with deconvwnrI am trying to deblur a motion-blur with deconvwnr , but the results is very poor
hers is the code :
% %first step: motion blurring
Len = 20; % linear motion of the camera given in pxels
Theta = 135; %angle of the motion given in conter-clockwise direction
h = fspecial('motion',Len,Theta);
f_blurred = imfilter(f,h,'conv','replicate');
% using deconvwnr for deblurring :
NSR = 0; %no noise
deblurred = deconvwnr(f_blurred,h,0);
the below image is the result, as you see it is extremely corrupted, why is that ?
when I changed the noise-parameter slightly it became a bit more visible, but still poor. My image is only blurred, no noise, shouldnt wiener work much better with this simple type of motion blur?
Her is the original image :
Edit: I think I have understood why it look so corrupted. When we set the noiseparameter to zero, the wiener filter is identical to the inverse filter, and since we divide by numbers very close to zero these values blows up and it corrupts the rest of the image.Eirik Kvernevikhttps://uk.mathworks.com/matlabcentral/profile/authors/21364707tag:uk.mathworks.com,2005:Question/7647362021-03-06T11:41:21Z2021-03-06T13:13:57ZIntegration using quad helpCan anyone explain why I am having an error
"Error in quad (line 67)
y = f(x, varargin{:});"???
I am trying to integrate e^(x)/((10*x)-1) with limits 0 to 200
y1 = quad('((exp.^(x)./((10.*x)-1)))',0,200)Ashis Pandeyhttps://uk.mathworks.com/matlabcentral/profile/authors/21436925tag:uk.mathworks.com,2005:Question/7646512021-03-06T10:24:31Z2021-03-06T13:07:00ZWriting a structure to a txt fileI have a structure which contains some parameters for a function:
F1Parameters.adaptedThresholdValue = 0.38;
F1Parameters.BWopenValue = 800;
F1Parameters.seDiskValue = 32;
I want to be able to write this to a text file in the following format, which keeps the structure name as the first column.
Function Parameter Value
F1_Parameters adaptedThresholdValue 0.38
F1_Parameters BWopenValue 800
F1_Parameters seDiskValue 32
To do this, I'm using the code below, but this seems like a very inefficient way to do it - am I missing an obvious way of just exporting the structure with the structure name as the first column?
% write F1 parameters to a txt file
table_F1Parameters = struct2table(F1Parameters); % convert F1 parameters to table
transposed_F1Parameters = rows2vars(table_F1Parameters); % transpose table
column_F1 = (repelem("F1_Parameters",height(transposed_F1Parameters)))'; % create new column to label F1, repeat name of structure
column_F1 = array2table(column_F1); % convert new column to table
final_F1_table = [column_F1,transposed_F1Parameters]; % concatenate column and table
final_F1_table.Properties.VariableNames = ["Function","Parameter","Value"]; % rename headers
writetable(final_F1_table,sprintf("%s",myFolderOutput,"Parameters"),"Delimiter","tab"); % write table to txt fileBChttps://uk.mathworks.com/matlabcentral/profile/authors/17076341tag:uk.mathworks.com,2005:Question/7647312021-03-06T11:38:08Z2021-03-06T13:05:57ZButterworth Bandpass Filter DesignWhy [b,a] = butter(n,Wn,'bandpass') designs a Butterworth filter of order 2n?
How to design an odd-order Butterworth filter with this command? Kam Shahttps://uk.mathworks.com/matlabcentral/profile/authors/11625001tag:uk.mathworks.com,2005:Question/7429322021-02-11T18:52:34Z2021-03-06T13:03:44ZHow do I get a Function to run inside a program?Hi, I am missing something in getting this function to run. Functions are new to me. This is a function in a bigger program of mine but it isn't executing. Thanks for the help.
Allan
function Check_IB_Open_Positions
fprintf('************************************** \n');
fprintf('Checking IB Positions for Sell Signals \n');
fprintf('************************************** \n');
% 1. Check IB For any existing LONG Position and check for a close Signal
% Get Stock Name
% Get marketPrice
% Get averagePrice
% Get Quantity
% 2. Check IQFEED for Latest Data and calculate the Stochastic
%Perform Profit Check If TRUE then complete 'Close Signal Check'
openPositions = IBMatlab('action','symbol','portfolio'); pause(1)
% Loop over all open positions (array of structs)
for posIdx = 1 : length(openPositions)
% Get the next open position
thisPosition = openPositions(posIdx); % thisPosition is a struct
symbol = thisPosition.symbol;
% Skip this position if it's not really open (position qty = 0)
position = thisPosition.position;
if position == 0, continue, end
% Compare the position's reported market price and its average price.
% If marketPrice > averageCost, proceed to CLOSE_LONG_POSITION_SIGNAL CONDITION
marketPrice = thisPosition.marketPrice;
averageCost = thisPosition.averageCost;
closeLongPosition = marketPrice > averageCost;
% If LongProfitCheck is TRUE the check stochastic for 'CLOSE_LONG_POSITION_SIGNAL'
if closeLongPosition % CLOSE_LONG_POSITION_SIGNAL CONDITION
CloseLongStep4 = True;
if CloseLongStep4
% Closing Position at marketPrice +/- some extra percent
% (depending on whether the position is long or short)
factor = 1 + 0.0001*sign(position);
Close_Limit_Price = round(marketPrice * factor, 2);
%fprintf('******** CLOSING EXISTING LONG POSITION ******** \n');
fprintf('%-5s => closing open position (%g) at $%.2f\n', symbol, position, Close_Limit_Price);
IBMatlab('action','CLOSE', 'Symbol',symbol, 'type','LMT', 'LimitPrice',Close_Limit_Price);
else
% do nothing
end
end
end
endAllan Munrohttps://uk.mathworks.com/matlabcentral/profile/authors/17869019tag:uk.mathworks.com,2005:Question/7647662021-03-06T12:34:08Z2021-03-06T12:54:19Zoverall area of intersecting rectanglesHi all, I have multiple rectangles defined by the rectangle() function, as seen in picture 1. The Hight and Width of the rectangles are variables. The positions of the rectangles are affected by each other, so if if the red rectangle gets bigger, the other rectangles will shift along the x- and y- axes.
I want to calculate the overall Area, so basically as shown in picture 2, the area between the axes and the outermost rectangle boundaries.
Any help is appreciated, thanks!
Tobias Eißlerhttps://uk.mathworks.com/matlabcentral/profile/authors/20197877tag:uk.mathworks.com,2005:Question/7647012021-03-06T11:22:56Z2021-03-06T12:51:27ZHOW CAN I SOLVE THIS?Ting Yu Leehttps://uk.mathworks.com/matlabcentral/profile/authors/21613199tag:uk.mathworks.com,2005:Question/7647212021-03-06T11:26:55Z2021-03-06T12:40:43ZConcatenate matrices not the same size - without NaNHello,
I am trying to concatenate several matrixes having different sizes (rows and columns).
In order to have the same number of rows and columns so they can be concatenated, I want all the non-existant values of the smaller matrices to fill up with a constant value, so that in the end, all matrices have the same dimensions, which are the greatest number of lines among all matrices by the greatest number of columns among the matrices.
So, to sum up: I have, for example, two matrices A = [1 2 3; 4 5 6; 7 8 9] and B = [1 2; 3 4], and I want a 3D-matrix C = [1 2 3; 4 5 6; 7 8 9] and [1 2 a; 3 4 a; a a a] (with 'a' a given constant).
I tried to do this with the fillmissing function, but it seems it only works when there are NaN in the matrices? Here my matrices are images so the pixels I want to add don't exist at all.
Is there an existing function for this, or do I have to do it "manually"?
Thank you!
NicolasNicolashttps://uk.mathworks.com/matlabcentral/profile/authors/8971460tag:uk.mathworks.com,2005:Question/7647712021-03-06T12:34:51Z2021-03-06T12:34:51Zdeeplearning : how to increase the datasethow can i merge the data store and augmented datastore so that i can increase the number of images of my data setCHANDRA PRABHA Rhttps://uk.mathworks.com/matlabcentral/profile/authors/4555520tag:uk.mathworks.com,2005:Question/7647612021-03-06T12:30:03Z2021-03-06T12:30:03Zrms plot of voltage sag during faultsI want to get rms plot for a fault voltage like this using simulink. kindly help.
S POORNIMAhttps://uk.mathworks.com/matlabcentral/profile/authors/8337256tag:uk.mathworks.com,2005:Question/4563912019-04-15T07:26:27Z2021-03-06T12:27:18ZThe intersection of three cylindersHi everyone. I want to plot and create the intersection of 3 perpendicular cylinders.
Your help would be greatly appreciated!!Hirasawa Yuihttps://uk.mathworks.com/matlabcentral/profile/authors/13368888tag:uk.mathworks.com,2005:Question/7615662021-03-03T12:22:43Z2021-03-06T12:26:44ZHow to create calcium traces of individual neurons and club them together in one representation (see image for reference)?I am trying to create one figure which consists of individual calcium traces of neurons.Also, I am new to matlab. Yojet Sharmahttps://uk.mathworks.com/matlabcentral/profile/authors/12082636