https://uk.mathworks.com/matlabcentral/answers/questionsMATLAB Answers — New Questions2020-10-27T10:17:36Ztag:uk.mathworks.com,2005:Question/6274082020-10-27T08:27:48Z2020-10-27T10:14:22Zone size image for CNNHi, im new in mathlab!
i preprocced few image for CNN how can i make all image one size for import in NNtool?Samira Hashemihttps://uk.mathworks.com/matlabcentral/profile/authors/15781639tag:uk.mathworks.com,2005:Question/6274832020-10-27T10:14:08Z2020-10-27T10:14:08ZHow to select between two identically named built-in functions?Hello,
I was trying to use resample function from Signal Processing Toolbox. However, when trying to select the function, built-in function from timeseries was called. I couldn't find instructions how to select function from another Toolbox if there are two identically named functions.
I'd really appreciate if someone could explain how to select between two identically named built-in functions from different Toolboxes? Do I need to rename other function or in some other way select the other function?
I can see by calling which resample that by default it's calling function from timeseries (link: https://www.mathworks.com/help/matlab/ref/timeseries.resample.html) .
One that I want to use is described here: https://www.mathworks.com/help/signal/ref/resample.htmlMartti Ilvesmäkihttps://uk.mathworks.com/matlabcentral/profile/authors/18358394tag:uk.mathworks.com,2005:Question/2037392015-04-15T20:11:00Z2020-10-27T10:11:48Zhow can i code in matlab to find the optimal parameter of function
There is a function Q(t)= a1*A(t)+ a2*B(t)+ a3*A(t)^2*B(t)+ a4*A(t)*B(t) ^2+a5* B(t) ^3+ a6 A(t) ^3+ a7*A(t) ^2*C(t)
Where P(t), A(t), B(t) and C(t) are known for any point of time or a sample of time.
Then I want to obtain the value of a1, a2, a3,a4,a5,a6,a7 with constrained a1>0, a2<0, a3>0,a4>0, a6>0, a5 and a7 unbounded
So that P(t)-Q(t) become minimum or negligible at any point of time.prakash kumarhttps://uk.mathworks.com/matlabcentral/profile/authors/5289919tag:uk.mathworks.com,2005:Question/6268982020-10-26T19:37:05Z2020-10-27T10:11:44ZWhy do my EditField / TextArea not get updated? Hello everyone,
I am currently writing an app with AppDesigner to plot some variables.
I have a ListBox containing the variable names I have listed in a table. In that table I also have the path information of the variable.
I am trying to display that path information in a TextArea or in an EditField, however they stay empty.
I've tried to solve this with these lines in the ListBox-function
function VariablesListBoxValueChanged(app, event)
app.VariablesListBox.ItemsData = 1:length(app.VariablesListBox.Items);
SelectNum = app.VariablesListBox.Value;
load s; % s is the table which I already loaded with another button
SelectPath = s.Y(SelectNum).Path;
set(app.VariableTextLabel, 'Text', SelectPath);
app.VariablePathTextArea.Value = SelectPath
save SelectNum;
save SelectPath;
end
and with these ones in the PushButton-function
function ShowButtonPushed(app, event)
load s;
load SelectNum;
load SelectPath;
set(app.VariableTextLabel, 'Text', SelectPath);
end
but nothing seemes to be working.
I am very helpful for every piece of advice. Many thanks in advance!Blanca R.https://uk.mathworks.com/matlabcentral/profile/authors/16945155tag:uk.mathworks.com,2005:Question/6201982020-10-20T14:49:19Z2020-10-27T10:11:01Zhow can i display video and image simultaneously in GUI-matlab?
Hi everyone,
Anybody knows that how can I display a video and a picture in two different windows simultaneously (with 1 pushbotton and without dilay in GUI)? I used the following code but the imgae (in second window-axes(handles.axes2)) is diplayed after finishing the video. I need to start both at the same time.
Thanks in advance.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
axes(handles.axes1);
vidObj = VideoReader('Try.avi');
numFrames = 0;
while hasFrame(vidObj)
F = readFrame(vidObj);
numFrames = numFrames + 1;
imagesc(F)
drawnow
end
numFrames
axes(handles.axes2);
imshow('index.jpg');Koohyarhttps://uk.mathworks.com/matlabcentral/profile/authors/19159059tag:uk.mathworks.com,2005:Question/6274132020-10-27T08:33:01Z2020-10-27T10:10:03ZHow to get value of X based on a specific value of Y in GraphHow to get value of X based on a specific value of Y in Graph
for example
x = [ 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 ];
y= [ -77.4236 -91.4051 -105.387 -119.368 -133.35 -147.331 -161.313 -175.294 -189.276 -203.258 ]
and i have to find at what value of x i m getting y value of 100 or any negative value of Y.
ayinashttps://uk.mathworks.com/matlabcentral/profile/authors/15649154tag:uk.mathworks.com,2005:Question/6236732020-10-23T09:44:23Z2020-10-27T10:09:43ZFind the certain amount of values between NaNs and make another variable from these valuesHi!
I have a matrix A which has 50 rows and 15000 columns with some numbers and sometimes NaNs between them. In each of these rows I want to find periods of time when the continuous length of non-NaN values was not shorter then 270 (but it can 300, 500 or longer, whatever). I want to take 270 first values out from each of these epochs and make another variable from it. Is it somehow possible?
Just an example:
A = 1 2 3 NaN NaN NaN NaN NaN 4 5 NaN NaN NaN 6 7 8 9 10 NaN NaN
NaN NaN 1 2 3 4 NaN NaN NaN NaN 5 NaN NaN NaN 6 7 8 9 10 NaN
1 NaN NaN NaN 2 3 4 NaN NaN 5 6 NaN NaN 7 8 9 10 11 NaN NaN
I want to find the epochs when the number of values between NaN is 3 or more (for example). And then I take the first 3 elements of the epoch and put it to the new line of the new variable. In the end my new variable should look like this:
result = 1 2 3
6 7 8
1 2 3
6 7 8
2 3 4
7 8 9
I hope I explained clearly.
Thanks for any help!Daria Ivanchenkohttps://uk.mathworks.com/matlabcentral/profile/authors/12093337tag:uk.mathworks.com,2005:Question/6266632020-10-26T16:19:40Z2020-10-27T10:09:15ZFind sorrunding elements and element from a array I have an array
y = [
0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0]
where Index 7,41,75 are the locations where 1 is found .
My requirement is
create a block around true(1) with a size of 5
get the indices like 5,6,7,8,9 and data 0 0 1 0 0
Matlabhttps://uk.mathworks.com/matlabcentral/profile/authors/7949204tag:uk.mathworks.com,2005:Question/5557092020-06-27T11:56:22Z2020-10-27T10:08:21ZColored gradient fill under curveI know this is not the most elegant solution, but it works. Indeed, I am a beginner, so excuse me. My question is, how to simplify it all?
Here's what I want to achieve: I have a 2D plot and I want to make a gradient fill under curve. From one specific color to transparent. I tried to use white instead of transparent, but I want the grid to be visible. So I'm little lost here.
Did some search and I looked for some examples here and tried to modify them. So, this is an edited code that worked to fill a specific range. I spread it all over the axis. I also didn't want to fill the gradient over the edge of the curve, so I had to insert plot again. Yeah, that's not ideal at all, but as I said, it's working.
I believe that this can be done more easily. Could you advise me, please?
% Input data
x = 0:0.01:10*pi;
y1 = sin(x)+9;
y2 = repmat(5,length(y1),1);
figure1 = figure;
plot(x,y1);
grid on;
hold on;
% Fill the whole area - 0-31.4
val = [0,31.4];
for i = 1:2;
tmp = abs(x-val(i));
[~,idx(i)] = min(tmp);
end
id = idx(1):1:idx(2);
x2 = x(id);
y1a = y1(id);
y2a = y2(id);
y2a = y2a';
X=[x2,fliplr(x2)];
Y=[y1a,fliplr(y2a)];
% I set the transparency and removed borders.
% This is a workaround, I don't want to set the whole transparency.
h = fill(X,Y,Y,'LineStyle','none');
set(h,'facealpha',.5)
% Here is how I made the gradient between red and white.
% This is not very nice solution and I would like to simplify it.
% Of course, color bar is not visible.
set(gca,'Colormap',[1 1 1; '...a lot of data...' ;1 0 0]);
% Need to plot again because of overlaping
plot(x,y1);
Leohttps://uk.mathworks.com/matlabcentral/profile/authors/9939699tag:uk.mathworks.com,2005:Question/6274732020-10-27T09:55:57Z2020-10-27T10:05:01ZPLEASE HELP ME :((ali velihttps://uk.mathworks.com/matlabcentral/profile/authors/2180604tag:uk.mathworks.com,2005:Question/6242382020-10-23T19:23:10Z2020-10-27T10:02:23Zkeep "Error: File: nozzlecalculator.m Line: 24 Column: 19 Local function name must be different from the script name".What i posted below is a part of a function scriptnamed nozzelcalculator, so when try calling it from main script i get this error.function outlet = nozzlecalculator(Athroat,Aexit,Pstagnation,Pback)
if Athroat < Aexit
output('user input is valid')
else
error('Athroat must be less than Aexit')
end
% Calculate the first critical pressure (Pc1)
Mexit = areamachnumber(Athroat,Aexit,false);
Pc1 = staticpressure(Pstagnation,Mexit);
endTHABANG MONOANEhttps://uk.mathworks.com/matlabcentral/profile/authors/17687660tag:uk.mathworks.com,2005:Question/6274632020-10-27T09:42:51Z2020-10-27T09:58:07ZHow to store data of FOR LOOP iteration?In the following code i want all the data of each iteration to be stored in P_new, and also B_xq, B_xq , B_xq repectively, but what i get is only the last one. What needs to be changed in my code?
k = convhull(data_coord);
for i = 1:length(k)
v1_x = x_data(k(i,1));
v1_y = y_data(k(i,1));
v1_z = z_data(k(i,1));
v2_x = x_data(k(i,2));
v2_y = y_data(k(i,2));
v2_z = z_data(k(i,2));
v3_x = x_data(k(i,3));
v3_y = y_data(k(i,3));
v3_z = z_data(k(i,3));
p1 = [v1_x v1_y v1_z];
p2 = [v2_x v2_y v2_z];
p3 = [v3_x v3_y v3_z];
ps = [p1; p2; p3];
p12 = p2-p1;
p23 = p3-p2;
P = [p12; p23];
q = sqrt(rand(5, 1));
q = [q q.*rand(5, 1)];
P_new = q*P+p1;
F_Bx = scatteredInterpolant(data_coord, B_x,'nearest');
B_xq = F_Bx(P_new(:,1),P_new(:,2),P_new(:,3));
F_By = scatteredInterpolant(data_coord, B_y,'nearest');
B_yq = F_By(P_new(:,1),P_new(:,2),P_new(:,3));
F_Bz = scatteredInterpolant(data_coord, B_z,'nearest');
B_zq = F_Bz(P_new(:,1),P_new(:,2),P_new(:,3));
endNimahttps://uk.mathworks.com/matlabcentral/profile/authors/13687446tag:uk.mathworks.com,2005:Question/5858332020-08-28T15:08:32Z2020-10-27T09:55:00ZCoder Structure element Size Mismatch error during subscriptingHi
I am facing Size mismatch error while performing array operation with structure .I need help in resolving the issue
Impnse.isOut(:,idx) = memfcn(1:size(Impnse.f(:,idx),1),locs);
Error Message : Size mismatch ([441000 x 1] ~= [:? x 441000])
f = zeros(441000, 2)
isOut = zeros(size(f,1),2);
Input Impnse = struct('f',f ,'isOut' ,isOut);
Impnse.isOut(:,idx) = memfcn(1:size(Impnse.f(:,idx),1),locs);
size(1:size(Impnse.f(:,idx),1))
ans =
1 441000
size(locs)
ans =
1423 1
size(Impnse.isOut(:,idx))
ans =
441000 1
Size mismatch ([441000 x 1] ~= [:? x 441000])
Matlabhttps://uk.mathworks.com/matlabcentral/profile/authors/7949204tag:uk.mathworks.com,2005:Question/6273632020-10-27T07:37:23Z2020-10-27T09:53:30Zinterpolation of data takes minutes to operateI have a data of 5068x59 and I want to interpolate each column with respect to column number 4. I have used the below code and its working fine. However, it takes sometime to operate. Therefore, is there any easier way to perform the below tasks
T=readmatrix('1.xlsx');
x = T(:,4) ;
for b=1:width(T)
for bb=1: length(x)
T1(bb,b)=T(bb,b)+ bb*1E-11; %to make all values unique
end
end
distanceQ = 1:max(T1(:,4)); % new distance vector with step size of 1m
for cc=1:width(T1)
speedQ = interp1(T1(:,4),T1(:,cc) , distanceQ);
filename = 'x)Data.xlsx';
writematrix(speedQ,filename,'WriteMode','append')
endAbdulkarim Almukdadhttps://uk.mathworks.com/matlabcentral/profile/authors/19918447tag:uk.mathworks.com,2005:Question/856192013-08-26T11:45:26Z2020-10-27T09:51:14Zwhat is asv file in matlab and how to open it?*|bold|*divya singhhttps://uk.mathworks.com/matlabcentral/profile/authors/4102239tag:uk.mathworks.com,2005:Question/6274682020-10-27T09:48:26Z2020-10-27T09:48:26Z*Function for increasing density and thickness with depthI'm trying to make a function that creates a profile of randomised values (within a range) corresponding to increasing density and thickness of a body with depth. I have a 600 x 2 array with the first column indicating depth (0-600) and the second density (250-900). I've made the first part of my function, implemented the randomisation over a range but now I want to add some functionality wherby as we cycle through each successive row (depth) we select multiple adjacent rows that also get randomised values. So effectively, as we go deeper we select an increasing number of rows for randomisation of density values giving the impression of thicker areas layers being selected. The grpah should look something like I've plotted below but with layers of increasing thickness as we go deeper. I've added what I wrote so far below. I know its probably not efficient so any reccomendations for improving it are welcome.
Base = DP_1989{1:1200,2};
Diff = zeros(1000,1);
for i = 1:length(Base)
Diff(i) = 917 - Base(i);
end
% Pick a random number that generates a random number of ice lenses
rl = round(100.*rand(1,1));
% Index positions for each lens (number between 10:1000)
index = round((1000-10).*rand(rl,1) + 10);
% empty array for new density values
new_density = zeros(1200,1);
% Generate new density values
for i = 1:rl
index(i)
new_density(index(i)) = (917-Base(index(i))).*rand(1,1) + Base(index(i)) ;
end
% Store them somewhere
for i = 1:rl
Base(index(i),2) = new_density(index(i));
end
%Convert original density profile from table to an array
DPtab = table2array(DP_1989(:,(1:2)));
%Insert new density values
for i = 1:rl
DPtab(index(i),2) = Base(index(i),2);
end
% Convert back to table, plot
DP_new = array2table(DPtab);
figure;
x2 = DP_new{:,2};
y2 = DP_new{:,1};
plot(x2,y2)
ylim([0 100])
xlabel('Density(kg m^{⁻3})');
ylabel('Depth(m)');
set(gca, 'YDir','reverse') % Reverses direction of axis so surface is top of y axis
Tom Edwardshttps://uk.mathworks.com/matlabcentral/profile/authors/6888662tag:uk.mathworks.com,2005:Question/6239782020-10-23T14:40:31Z2020-10-27T09:42:29ZIs there an equivalent serialbreak() function with the new serialport class in MATLAB 2020b?MATLAB is recommending the switch to serialport as opposed to serial. With the old serial class, you could send a serialbreak() command. With the new serialport() class, I cannot locate a similar functionality. Is there a way to do this? Thanks.
------------------------------------------------------------------------------------
% Old way.
mbed = serial('COM9');
fopen(mbed);
serialbreak(mbed,1);
% New way.
mbed = serialport('COM9',9600);
% How do I send serial break with this new class?
Matthew Feemsterhttps://uk.mathworks.com/matlabcentral/profile/authors/292692tag:uk.mathworks.com,2005:Question/5025722020-01-29T12:09:05Z2020-10-27T09:41:33ZDifferent assignment of coordinates in meshgrid().Dear all,
I guess my question is simple to answer, however I am stuck.
I have data in 3d space stored in a 3D array, where the columns are the y coordinate, the rows the z coordinate and the "depth" of the matrix is the x-coordinate. Now I'd like to plot the data with slice and quiver but just can't figure out how to assign x, y and z in my coordinate system to the meshgrid function in order to get the right coordinate grids.
Any help or insight you can provide is very much appreciated.Andre Riegerhttps://uk.mathworks.com/matlabcentral/profile/authors/16027539tag:uk.mathworks.com,2005:Question/6199532020-10-20T11:30:45Z2020-10-27T09:40:36Z(App Designer) show the variables from another function, in a dropdown?I have loaded a file, and in a dropdown list I would like to have the variables from the loaded file, with which I can work and show graphics after selecting one of the variables(in the dropdown)?
My variables contain always values in a Matrix or array.Dibran Kodrahttps://uk.mathworks.com/matlabcentral/profile/authors/17705916tag:uk.mathworks.com,2005:Question/2783002016-04-11T05:33:53Z2020-10-27T09:40:06ZMatlab code help on Euler's MethodI have to implement for academic purpose a Matlab code on Euler's method(y(i+1) = y(i) + h * f(x(i),y(i))) which has a condition for stopping iteration will be based on given number of x. I am new in Matlab but I have to submit the code so soon. I am facing lots of error in implementing that though I haven't so many knowledge on Matlab. If anyone provide me so easy and simple code on that then it'll be very helpful for me. Thank you.Sanjida Ahmedhttps://uk.mathworks.com/matlabcentral/profile/authors/7625469tag:uk.mathworks.com,2005:Question/6274432020-10-27T09:05:34Z2020-10-27T09:37:26ZHow to write code for a function x(t), consist of two sine wave with instantaneous frequencies at different time spot as seen in figure below:Could any one help me how to write the Matlab code for this function in order to plot the Hilbert spectrum?
Jan Alihttps://uk.mathworks.com/matlabcentral/profile/authors/17449316tag:uk.mathworks.com,2005:Question/6249332020-10-24T16:48:41Z2020-10-27T09:37:16Zwmsread 3D output explanationI can't understand the three-dimensional output of the function wmsread. I don't understand how to read it and how to connect the data it contains to latitude and longitude. (So how is the data connected to the position in the output 3D matrix?) Could someone explain it to me? Please. I have to construct a matrix with data from wmsread Chiara Zulianihttps://uk.mathworks.com/matlabcentral/profile/authors/13726852tag:uk.mathworks.com,2005:Question/6216632020-10-21T17:57:40Z2020-10-27T09:36:48ZHow to solve multivariable ODEI have the equations:
dx/dt = 2 - 0.09x + 0.038y
dy/dt = 0.066x - 0.038y
x(0) = 0
y(0) = 0
Ultimately I need to solve the ODE and plot for x and y versus time (t). I just don't know how to code for the equations in Matlab.
ThanksJessica Dominichttps://uk.mathworks.com/matlabcentral/profile/authors/18100639tag:uk.mathworks.com,2005:Question/6274582020-10-27T09:35:04Z2020-10-27T09:35:04ZWhich module is best for modeling large cell populations?Can Simbiology be used for this or is base Matlab enough? Is there another module which is better?Ekaterina Trapitsynahttps://uk.mathworks.com/matlabcentral/profile/authors/11349183tag:uk.mathworks.com,2005:Question/6236232020-10-23T08:40:07Z2020-10-27T09:30:28ZHow to create multiple slides in Presentation Generator?Hello, I am fairly new to Matlab and I still struggle with loops and indexing.
I would like to add to my Power Point presentation a number of slides that correspond to the number of files in a folder.
Using dir() i get the number of files and I would like to create somtehing like:
import mlreportgen.ppt.*;
slidesFile = 'mySlides.pptx';
slides = Presentation(slidesFile);
files = dir(my_folder);
s = length(files)
for
i = 1:length(files)
slide{i} = add(slides,'Title and Content');
replace(slide{i},'Content', i_stfile.png});
end
close(slides);
I am trying to figure out the correct indexing syntax.
I would be very grateful for any helpAnna Wachnowiczhttps://uk.mathworks.com/matlabcentral/profile/authors/19141350tag:uk.mathworks.com,2005:Question/3316892017-03-24T08:07:46Z2020-10-27T09:24:01ZWhy is there no 'ExecutionEnvironment' parameter for trainingOptions function?I am using a macbook pro with no nvida gpu, by default trainNetwork should use cpu instead of gpu. But I got this error.
There is a problem with the CUDA driver or with this GPU device. Be sure that you have a supported GPU and that
the latest driver is installed.
Error in parallel.internal.gpu.isAnyDeviceSelected
Error in parallel.gpu.GPUDevice.current (line 33)
if parallel.internal.gpu.isAnyDeviceSelected
Error in gpuDevice (line 23)
dev = parallel.gpu.GPUDevice.current();
Caused by:
The CUDA driver could not be loaded. The library name used was '/usr/local/cuda/lib/libcuda.dylib'. The error
was:
dlopen(/usr/local/cuda/lib/libcuda.dylib, 10): image not found"
Then I tried to follow the documentation to use cpu <https://www.mathworks.com/help/nnet/ref/trainingoptions.html>
, my matlab 2016a says trainingOptions doesn't have 'ExecutionEnvironment' parameter.
This is my code
opts = trainingOptions('sgdm',...
'ExecutionEnvironment','cpu',...
'LearnRateSchedule','piecewise',...
'LearnRateDropFactor',0.2,...
'LearnRateDropPeriod',5,...
'MaxEpochs',20,...
'MiniBatchSize',300);
Error using nnet.cnn.TrainingOptionsSGDM.parseInputArguments (line 115)
'ExecutionEnvironment' is not a recognized parameter. For a list of valid name-value pair arguments, see the
documentation for this function.
Error in trainingOptions (line 97)
args = nnet.cnn.TrainingOptionsSGDM.parseInputArguments(varargin{:});Rongbing Muhttps://uk.mathworks.com/matlabcentral/profile/authors/9579186tag:uk.mathworks.com,2005:Question/6271732020-10-27T01:55:07Z2020-10-27T09:21:56ZSegment audio file using timeI have a .wav file ( song.wav ) that is 5s long, I have time_start= 3.23s and time_end=4.35s and another sing.wav that is 4s long with time_start1=2.38s and time_-end1=3.56s. I want to store the segments of song.wav and sing.wav that start respectively are time_start and time_start1 and end at time_end and time_end1 into a cell array. How do I start? The answer I've seen so far were cutting the file in terms of Fs, that's not itMelissa Ettehttps://uk.mathworks.com/matlabcentral/profile/authors/19783382tag:uk.mathworks.com,2005:Question/6245932020-10-24T08:21:40Z2020-10-27T09:21:39Zfixed time step for ODE45 Hi,
aakash here.
I have written the code below to solve the second order ODE using ODE45. There is an event condition in my code. Because of presence of this event condition, I am not (i dont know) able to use fixed time step in ODE45. Can somebody please help me with this. I request all to please help me to add the fixed time step in this code.
Waiting for the responses.
Thank you
~aakash
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clc
clear all
close all
global k Th0 e m c t
%% Input parameters (Length (L), co-efficient of restitution (e), acceleration due to gravity (g))
e=0.9; m=1; c=0; k=246.46;
%% Initial condition
Thid = 8*40/(5*pi)^3; % position from where the mass is released
Thiv = 0; % inital velocity (at t=0)
Th0 = 0.05; % Position where the wall is there
tfi = 5; % time final time
%% ode45 (function call)
eta0=[Thid Thiv]; % Initial conditions
tspan=[0 tfi];
options = odeset('Events',@aakash_function);
t_vec = [];
eta_vec = [];
tcon=0;
ii=1;
while tcon<tfi %% to check whether final time is reached or not
tspan=[tcon tfi];
[t,eta] = ode45(@aakash_mass,tspan,eta0,options);
eta0=[eta(end,1) -(e*eta(end,2))]; %% modified inital conditions after impact
tcon=t(end,1);
t_vec = [t_vec;t];
eta_vec = [eta_vec;eta];
end
t_vec = [t_vec;t];
eta_vec = [eta_vec;eta];
%%
syms u5 x
u5 = sin(5*pi*x)*eta_vec(:,1)
%% Plot
% close all
for i = 1:length(u5)
fig = ezplot(u5(i))
set(fig,'Linewidth',1.5)
xlim([0 1])
ylim([-0.25 0.25])
grid on
title('only third mode')
pause(0.0000000000001)
endaakash dhttps://uk.mathworks.com/matlabcentral/profile/authors/19992803tag:uk.mathworks.com,2005:Question/6273582020-10-27T07:30:46Z2020-10-27T09:20:00ZHow to solve an ODE with 2 initial conditions and 2 unknown parameters and 3 boundary conditions (overdetermined?)I have an ODE of the form
where a and b are unknown parameters, and F(t) is a fractional function: e.g.
The initial conditions are
and
Because a and b are unknown, the soultion of the ODE is depeding on a and b.
The solution has to fulfill these boundary conditions in the time interval :
(where K is a known constant, e.g. )
( the maximum of the derivative of the solution is v, where v is a known velocity, e.g. )
The first problem is, that the linear system of equations to solve for a and b is overdetermined, because there are 3 eqantions for 2 unknowns. The second problem is, that i cant use the symbolic toolbox to compute the solution of the ODE, because of the broken rational function F(t) (it takes far too long, approx. more than 10 hours).
Would bvp4c or bvp5c be suitable for my problem? If so, then how to use them. And if not, is there anything else i could try?e_froghttps://uk.mathworks.com/matlabcentral/profile/authors/11358900tag:uk.mathworks.com,2005:Question/892432013-10-05T11:43:22Z2020-10-27T09:16:23ZSwitch two row of matrixHow to switch two row of matrix?
For example: matrix A is: 1 3 4; 2 4 5 and Y want to be 2 4 5; 1 3 4 ?
Dusan Grdichttps://uk.mathworks.com/matlabcentral/profile/authors/4667151tag:uk.mathworks.com,2005:Question/6274232020-10-27T08:53:07Z2020-10-27T09:14:44Zhow to generate and precise double value?Hello
I want to ask you How I can generate probability values randomly between 0 and 1, but 1 and 0 can include as probability value
for example
I have a vector of values X=[12 5 10 50 22]
each value of X must have a probability where 0<=p>=1
when I obtain probability like 0.98555 I want just pick 0.9
How I can do that.?
Please help me!Mira lehttps://uk.mathworks.com/matlabcentral/profile/authors/15555924tag:uk.mathworks.com,2005:Question/6274532020-10-27T09:12:37Z2020-10-27T10:17:36Zsearch in large cell fileHi all,
I'm looking for a function such that I can acces the following text in my SSD file (attached)
THE FOLLOWING TABLE IS PRINTED FOR NODES BELONGING TO NODE SET ASSEMBLY_DISPLACEMENT_NODE,
I open my SSD file according to:
clear all, clc, format longG
Counter = 1;
FID = fopen('SSD_anal - Copy.dat', 'rt');
tline = fgetl(FID);
File_Data{Counter} = tline;
while ischar(tline)
Counter = Counter+1;
tline = fgetl(FID);
File_Data{Counter} = tline;
end
fclose(FID);
File_Data = File_Data';
Which brings me a cell 76540x1 cell, I tried to find the indices by:
Index = find(contains(File_Data,'THE FOLLOWING TABLE IS PRINTED FOR NODES BELONGING TO NODE SET ASSEMBLY_DISPLACEMENT_NODE'));
and
IndexC = strfind(File_Data,'THE FOLLOWING TABLE IS PRINTED FOR NODES BELONGING TO NODE SET ASSEMBLY_DISPLACEMENT_NODE');
but nothing works, as it states that:
Error using strfind
Cell must be a cell array of character vectors.
Any clues how I could find the indices where the file states the statement above?
greetings and thanks for your help and attention already!Frank Oosterveldhttps://uk.mathworks.com/matlabcentral/profile/authors/4568417tag:uk.mathworks.com,2005:Question/6266132020-10-26T15:33:33Z2020-10-27T09:13:01Zmore then one tag on object in figureI have a problem whith a line of code in which i have 3 robots with each a seperate tool. Each tool has the tag tool1-3 depending on the robot now the tool is drawn with the line command inside a loop where it extracts vectorised x,y,z values from a struct. The loop is within another loop inside a switch case for each robot.
my initial thought was to maby declare more than one tag to the obj with the use of j for allocating the same line obj ones it's suppoed to redraw it.
code in which the problem stems is this one:
for j = 1: size(td,2) %the td = rd.xyz a
% V 4x4 matrix is the hand position of the robot in the x,y,z plane V(1:3,1:3) = rotation
% V(1:3,4) = translation
p = V(1:3,4); % This is for the starting position of the line
V(1:3,4) = V(1:3,4)+td(1:3,j); % P is the handposition rd.xyz from the TCP!
q = V(1:3,4); % this is the end position of the line from vector in td(:,j)
x = [p(1) q(1)];
y = [p(2) q(2)];
z = [p(3) q(3)];
if isempty(findobj('tag',['tool3',num2str(j)]))
h = line(x,y,z);
set(h,'tag',['tool3',num2str(j)],...
'color','k',...
'linewidth',3)
else
set(findobj('tag',['tool3',num2str(j)],...
'linewidth',3,...
'color','k',...
'xdata',x,...
'ydata',y,...
'zdata',z)
end
end
what i get is a figure that prints multiple tool lines as the robot moves and i need someway to redraw those away for the updated position of the tool.
the thing i'm getting at the moment looks like this:
I might be going at this all wrong and maby whould collect the vectors in seperate x(j) and y(j), z(j) arrays and ones those have been gathered draw the new line with or something.slowlearnerhttps://uk.mathworks.com/matlabcentral/profile/authors/15010996tag:uk.mathworks.com,2005:Question/6274382020-10-27T09:04:23Z2020-10-27T09:12:53Zhow to do Derivatives how can i derive fist and second Derivatives of y=2(x^2+1)/√(cos2x ),0≤x≤π/8aYOUB aLIhttps://uk.mathworks.com/matlabcentral/profile/authors/20111278tag:uk.mathworks.com,2005:Question/6244382020-10-24T00:13:15Z2020-10-27T09:10:54ZK-means Clustering for Image Segmentation to find sum of cluster's pixelsHello MATLAB community,
I've been using K-mean clustering for image segmentation; this is electron beam data. I've used to code below:
img = data.img(100:500,400:900); % Select the relevant part of the image
[L,Centers] = imsegkmeans(img,8); % Perform image segmentation with 8 centroids
B = labeloverlay(img,L);
imshow(B); % Display it
This code produces the following output:
There are 8 "islands" that represent a quantity that needs to be calculated. What I need to do is to calculated the pixels that account for these "islands". Any suggestions how I may be able to do this?Sebastian Bustillohttps://uk.mathworks.com/matlabcentral/profile/authors/18947810tag:uk.mathworks.com,2005:Question/6259582020-10-26T01:09:03Z2020-10-27T09:07:01ZI need help on cell array and Imaging processingHi
I am using the following code
close all;
clc;
%% Initalize the data
dataDir= fullfile('Data/');
exts = {'.jpg','.png','.tif','BMP'};
imds = imageDatastore(fullfile(dataDir),...
'IncludeSubfolders',true,'FileExtensions','.jpg','LabelSource','foldernames');
countEachLabel(imds);
[TrainData, TestData] = splitEachLabel(imds, 0.5);
size(TrainData);
countEachLabel(TrainData);
numImages = numel(TrainData.Files);
for i = 1:numImages
img = readimage(TrainData, i);
% img2= imshow(img, 'InitialMagnification', 800);
img3= imresize(img, [100 100]);
img4= imshow(img3, 'InitialMagnification', 800);
drawnow;
Train{i} = (img3); %#ok<SAGROW>
end
hiddenSize = 25;
autoenc = trainAutoencoder(Train,hiddenSize,'MaxEpochs',1000,...
'DecoderTransferFunction','purelin','EncoderTransferFunction','satlin','L2WeightRegularization',0.0004,'SparsityRegularization',4,'SparsityProportion',0.15);
numImages = numel(TestData.Files);
for i = 1:numImages
img5 = readimage(TestData, i);
img6= imresize(img, [100 100]);
img7= imshow(img3, 'InitialMagnification', 800);
drawnow;
Test{i} = (img6); %#ok<SAGROW>
end
xReconstructed = predict(autoenc,Test);
%% Test Images
figure();
for i = 1:10
subplot(4,5,i);
imshow(TestData.Files{i});
end
%% Reconstructed images from TestData
figure();
for i = 1:10
subplot(4,5,i);
imshow(xReconstructed(i))
end
But I got the following error
Error using imageDisplayValidateParams
Expected input number 1, I, to be one of these types:
double, single, uint8, uint16, uint32, uint64, int8, int16, int32, int64, logical
Instead its type was cell.
Error in images.internal.imageDisplayValidateParams (line 11)
validateattributes(common_args.CData, {'numeric','logical'},...
Error in images.internal.imageDisplayParseInputs (line 79)
common_args = images.internal.imageDisplayValidateParams(common_args);
Error in imshow (line 253)
images.internal.imageDisplayParseInputs({'Parent','Border','Reduce'},preparsed_varargin{:});
Error in data_process1 (line 51)
imshow(xReconstructed(i))
When I compare to the example,
https://www.mathworks.com/help/deeplearning/ref/trainautoencoder.html
the issue is with Train{i}and Test {i}, The model is not trained probably with given data. When I compared with example in MATLAB for digitTrainCellArrayData and digitTTestCellArrayData I am having problems and my cell array which are not the same as in example
My cell arrays for Train{i}and Test {i} are like this like for example Train{i}
But in the example in MATLAB for digits, digitTrainCellArrayData and digitTestCellArrayData are like this
digitTrainCellArrayData
In addition to that. Range in example is from 0 – 1 while my data is from 0 – 255
Kindly looking for your support Abdussalam Elhanashihttps://uk.mathworks.com/matlabcentral/profile/authors/15843739tag:uk.mathworks.com,2005:Question/6274482020-10-27T09:06:23Z2020-10-27T09:06:23ZFit ODE with scalar and vector inputsHi everyone,
I'm stuck with an ODE fitting and i was hoping someone could help me with my problem.
I am trying to fit a system of ODEs to experimental data, I've read several posts related to this topic but I can't seem to find a way to to pass inputs that are both a vector and a set of scalars to the function that solves the ODEs and ultimately lsqcurvefit. The code is the following:
function Z = model(p,t,u)
z0 = [rand rand rand]';
options = odeset('RelTol',1e-10,'AbsTol',1e-10,'Stats','on');
[T,Zv]=ode45(@(t,z)diff_eq(t,z,u),t,z0,options);
function dz = diff_eq(t,z,u)
zdot = zeros(4,1);
zdot(1) = z(2);
zdot(2)= p(1).*z(1)+p(4).*z(2)+p(5).*z(3)+p(2).*z(1).^2+p(6).*z(1).*z(3)...
+p(3).*z(1).^3+p(7).*z(1).^2.*z(3);
zdot(3) = p(8).*z(2)+p(11).*z(3)+p(14).*u+p(9).*z(1).*z(2)+p(12).*z(1).*z(3)...
+p(15).*z(1).*u+p(10).*z(1).^2.*z(2)+p(13).*z(1).^2.*z(3)+p(16).*z(1).^2.*u;
dz = zdot;
end
Z = Zv;
end
[p,Rsdnrm,Rsd,ExFlg,OptmInfo,Lmda,Jmat]=lsqcurvefit(@(p,t)model(p0,z,volt_est_avg),p0,t,z);
fprintf(1,'\tParameters:\n')
for k1 = 1:length(p)
fprintf(1, '\t\tp(%d) = %8.5f\n', k1, p(k1))
end
pfit = model(p,t);
p is a vector containing a set of scalars that I would like to oprimize to get thet best fit possible to the experimental data. u, on the other hand, represents an input to the system, and therefore it evolves during the same time as my state variables z.
Any help with this would be extremely precious, thank you very much in advance!Gresia Bacohttps://uk.mathworks.com/matlabcentral/profile/authors/11089794tag:uk.mathworks.com,2005:Question/5684162020-07-21T14:59:42Z2020-10-27T09:05:20ZDraw a bounding box for a 3D plot Hi,
I am working on a skeletonization problem and have managed to extract the skeleton of a 3D image volume. The skeleton is a 3D logical matrix. I now want to plot the skeleton as a 3D plot and do so within a bounding box. An example of what I want to achieve is shown below. It is the table of contents image for this journal article. I request the MATLAB community to please advice on how to get a plot like this. Thank you,
MaheshMahesh Ganesanhttps://uk.mathworks.com/matlabcentral/profile/authors/2923970tag:uk.mathworks.com,2005:Question/6219382020-10-21T21:51:18Z2020-10-27T09:03:02ZHow to detect the calling axes from context menu using AppDesignerHello Folks,
I hope you are all staying safe out there.
I am in the middle of a development project. So I have been posting several questions today (my apologies).
I am using App Designer to make an interconnected series of GUI's. One of the GUI's has many axes in it. I want to create a simple Context Menu that I can share between the different axes. I want the callback to get the current x and y limits of the axis, remind the user what they are, then accept input from the user to change it to something else. However, I can't seem to figure out how to get the handle of the axes within which the context menu was triggered from inside the callback. I have searched, but failed to find anything on this topic that I have recognized to be within the App Designer construct (lots of GUIDE construct posts though). Could any of you point me in the right direction?
Best regards,
Kris
Kristoffer Walkerhttps://uk.mathworks.com/matlabcentral/profile/authors/14436644tag:uk.mathworks.com,2005:Question/6274332020-10-27T09:00:45Z2020-10-27T09:00:45ZHow to optimize a linear system of complex-valued equations Hello everyone
I have a linear system of complex-valued equations as follows
ax + by = c
dx + ey = f
where a,b,c,d,e, and f are complex-valeued coefficients and x and y are my complex-valued unkonwns. I intend to conduct an algorithm like genetic algorithm to optimize "a" and "e" to get the optimized (min for example) value of "y". Would you please help me how I can manage to do this? thanks in advance for your time devoted to this question.Quantum Devourhttps://uk.mathworks.com/matlabcentral/profile/authors/9641417tag:uk.mathworks.com,2005:Question/6274182020-10-27T08:49:21Z2020-10-27T08:59:37ZLog Parsing using MATLABHello! Can someone help me with log parsing a file? I did searched videos and I get some parts of it like importing.
For example this is my file (data_file.txt)
98.140.180.244 - harber4797 [21/Jun/2019:16:01:53 -0700] "POST /seize/b2b/synergistic HTTP/2.0" 203 9396
54.92.231.149 - ziemann5634 [21/Jun/2019:16:01:54 -0700] "GET /revolutionize/matrix HTTP/2.0" 304 27968
205.98.120.209 - trantow6874 [21/Jun/2019:16:01:39 -0700] "PUT /front-end/world-class/partnerships/schemas HTTP/1.0" 401 25144
148.196.48.243 - ondricka6863 [21/Jun/2019:16:01:40 -0700] "GET /best-of-breed/reinvent HTTP/1.1" 501 29641
130.229.174.187 - hackett3055 [21/Jun/2019:16:01:41 -0700] "GET /sticky/deliver HTTP/2.0" 404 5708
if I input 'harber4797' to a function, how can I extract its whole line? What conditional works should I do? Thank youJoshua Mikhael Prietohttps://uk.mathworks.com/matlabcentral/profile/authors/13731927tag:uk.mathworks.com,2005:Question/6250332020-10-24T18:29:38Z2020-10-27T08:56:13Z(emd) How to get script/code from a figure/plot ?To plot emd for a function (x), I just write a synthetic signal and when I run emd(x), the signal components (imfs) will be shown on the figure. However, I want to know how the IMFs are created, and how to get the code for the given figure/plot.
Meanwhile, can any one share a code for imf ploting?Jan Alihttps://uk.mathworks.com/matlabcentral/profile/authors/17449316tag:uk.mathworks.com,2005:Question/6272182020-10-27T03:17:20Z2020-10-27T08:55:16ZHow can I plot this second-order differential equation
here is my start
for t1 = 0:100
for omega = 0.8:0.1:1.5
rhs = @(t,y) [y(2); -0.2.*y(2) + y - y.^3 + 0.3*cos(omega.*t)];
[t1, omega] = ode45(rhs, [0 6], omega);
plot (t1, omega);
end
end
could you help me?Hyun Suk Songhttps://uk.mathworks.com/matlabcentral/profile/authors/19363808tag:uk.mathworks.com,2005:Question/6246332020-10-24T09:16:06Z2020-10-27T08:54:47ZAvoid divergent curves of ODE solutionsHi all
I have solved a system of differential equations in an iterative way, as you can see from the graph I have several curves each of which is associated with a different combination of the iterative parameters. Again from the graph, it can be seen that some curves at a certain abscissa diverge; this is not acceptable so I would like to remedy it. Is it possible to create a new solution vector capable of avoiding the divergence as described below ?
I would like the solution not to diverge near the various cusp points and, on the contrary, to maintain the value immediately upstream of the latter, until the end of the domain. I'll explain: suppose we have the following solution values 1000 K,1020 K,2000 K,4000 K I would like instead: 1000 K,1020 K,1020 K,1020 K
Thank you for the help
Regards
T0=293;
delta_Thot=2500;%s
%%%%%%%%%%%%%
Nc_Thot=2;
[ya,sa,lea]=size(Aexposehot);
for y=1:yV%passo,altezza tubo,Rextbobbin,lunghezza cavo
for le=1:leV%lunghezza tubo equilibrio
for sv=1:sV%spessore parete3
% for k=1:km%Mach
for rf=1:length(Pressure_percentage_hot)
Rextbobb_cellhot(y)={Rextbobbin_fluxhot(y)};
Y0hot(y,le)={[T0,m0hot(y,le)]};
Dall_Th_hot ={[0:Nc_Thot:delta_Thot]};
Lequilibrium_cellhot(le)={Lequilibriumhot(le)};
Passo_cellhot(y)={Passo_fluxhot(y)};
hrad_cellhot(y)={Hradial_fluxhot(y)};
Spessore_parete3_cellhot(sv) ={Spessore_parete3hot(sv)};
Aexpose_cellhot(y,sv,le)={Aexposehot(y,sv,le)};
Volume_cell_Aisihot(le,y,sv)={Volume_Aisihot(le,y,sv)};
Volume_cell_gashot(y,le)={Volume_gashot(y,le)};
throat_cell_hot(y)={ThrtR_fluxhot(y)};
Pressure_end_chamber_hot_cell(rf)={Pressure_end_chamber_hot(rf)};
end
end
end
end
for iDom_Th = 1:numel(Dall_Th_hot)
for leLE=1:numel(Lequilibrium_cellhot)
for yY=1:numel(hrad_cellhot)
for rF=1:numel(Pressure_end_chamber_hot_cell)
for sS=1:numel(Spessore_parete3_cellhot)
TSol_hot(iDom_Th,yY,leLE,sS,rF)={zeros(length(Dall_Th_hot{iDom_Th}),2)};
end
end
end
end
end
opt_t_hot=odeset('NormControl','Refine','Stats','MaxStep');
for iDom_Th = 1:numel(Dall_Th_hot)
tRange_hot = Dall_Th_hot{iDom_Th};
for leLE=1:numel(Lequilibrium_cellhot)
for yY=1:numel(hrad_cellhot)
for rF=1:numel(Pressure_end_chamber_hot_cell)
for sS=1:numel(Spessore_parete3_cellhot)
Ltube_hot= Lequilibrium_cellhot{leLE};%L_cellhot{yY};
Leq_hot= Lequilibrium_cellhot{leLE} ;
Vol_Aisi_hot=Volume_cell_Aisihot{leLE,yY,sS};
Aexp_hot=Aexpose_cellhot{yY,sS,leLE};
Hradial_hot=hrad_cellhot{yY};
ThroatradiuS_hot=throat_cell_hot{yY};
Pressure_hot_end_chamber=Pressure_end_chamber_hot_cell{rF};
if Vol_Aisi_hot>0&&Leq_hot>0 &&Aexp_hot>0 &&Ltube_hot>0 && ThroatradiuS_hot>0&&Pressure_hot_end_chamber>0
[tSol{iDom_Th,yY,leLE,sS,rF},TSol_hot{iDom_Th,yY,leLE,sS,rF}]=ode23t(@(t,Y) ...
temperaturaheaterclassica(t,Y,Ltube_hot,Voltage1,Vol_Aisi_hot,Aexp_hot,ThroatradiuS_hot,Pressure_hot_end_chamber),tRange_hot,Y0hot{yY,leLE},opt_t_hot);
if(any(TSol_hot{iDom_Th,yY,leLE,sS,rF}(:,1)>1600))
% disp([ ' condizione verificata'])
%disp (iDom_Th)
disp(yY)
disp(leLE)
%disp(sS)
%disp(rF)
break
end
end
end
end
end
end
end
%end
[tT,yT,leT,sT,rFT]=size(TSol_hot);
for t = 1:tT
for y=1:yT
for le=1:leT
for s=1:sT
for rf=1:rFT
if TSol_hot{t,y,le,s,rf}(end,1)>0
figure(1);set(gcf,'Visible', 'on')
plot(tSol{t,y,le,s,rf}(:,1),TSol_hot{t,y,le,s,rf}(:,1))
xlabel('time [s]')
ylabel('Teq-transition/turbulent [K]')
hold on
end
end
end
end
end
end
EldaEbrithilhttps://uk.mathworks.com/matlabcentral/profile/authors/8447926tag:uk.mathworks.com,2005:Question/6274282020-10-27T08:53:14Z2020-10-27T08:53:14ZHow I get all frequency in FFT result?Hello,
I have a sine signal with many frewuency. I should get the frequency from FFT result.
Please let me know your suggestion.
I should generate the Fc values in frequencies element.
Fs = 5e4;
t = (0:Fs-1)*1/Fs; % Time vector
Datapoints = Fs;
Fc1 = 30:6/Fs:33; %(b-a)*2
Fc2 = sort(Fc1,'descend');
Fc = [Fc1 Fc2];
% % Select Variable amplitude
A1 = [1:64/Fs:9 3:96/Fs:15 5:24/Fs:8 2:16/Fs:4];
A2 = [2:48/Fs:8 4:24/Fs:7 1:32/Fs:5 3:24/Fs:6];
A = [A1 A2];
for i=1:length(t)
a_HZ = 2*pi*Fc(i)*t; % Set Frequency
sys(i) = A(i)*sin(a_HZ(i)); % FFT Output, A(i) Amplitude and a_HZ(i) is the changes in frequency
end
h = rand(1,4); % Random unknown system
r = filter(h,1,sys); % Input passed trought system(h)
y = awgn(r,30); % FFT Output Plus the random noise, white Gaussian noise to signal with SNR% Fourier Transformation
NFFT = Fs; % Next power of 2 from length of y
Y = fft(y,NFFT)/Fs;
fs= Fs/1;
[B,IX] = sort(2*abs(Y(1:NFFT))); %order the amplitudes
Amplitudes=(B) %find all amplitudes above the BFloor
Frequencies=Fc(IX) %frequency of the peaksfatemeh abdihttps://uk.mathworks.com/matlabcentral/profile/authors/19147991tag:uk.mathworks.com,2005:Question/6080512020-10-08T07:43:18Z2020-10-27T08:47:41Zissues with syms functionWhenever I use the syms (symbolic function) code I keep getting errors, even on simple codes that I am sure they are correct.
For example this simple code
syms a [1 4]
a
The output
Error in syms (line 227)
defined = sym(zeros(1, length(args)));
Error in quiz (line 1)
syms a [1 4]
Reem Alblooshihttps://uk.mathworks.com/matlabcentral/profile/authors/12086784tag:uk.mathworks.com,2005:Question/6178482020-10-18T15:34:01Z2020-10-27T08:44:45Zcode to detection the cars this code not counting cars properly How do i make it count correct ?clc
clear all
MV = imread('cars1.jpg'); %To read image
MV1 = imread('backgnd.jpg');
A = double(rgb2gray(MV));%convert to gray
B= double(rgb2gray(MV1));%convert 2nd image to gray
[height, width] = size(A); %image size?
h1 = figure(1);
%Foreground Detection
thresh=11;
fr_diff = abs(A-B);
for j = 1:width
for k = 1:height
if (fr_diff(k,j)>thresh)
fg(k,j) = A(k,j);
else
fg(k,j) = 0;
end
end
end
subplot(2,2,1) , imagesc(MV), title (['Orignal Frame']);
subplot(2,2,2) , imshow(mat2gray(A)), title ('converted Frame');
subplot(2,2,3) , imshow(mat2gray(B)), title ('BACKGND Frame ');
36;
sd=imadjust(fg);% adjust the image intensity values to the color map
level=graythresh(sd);
m=imnoise(sd,'gaussian',0,0.025);% apply Gaussian noise
k=wiener2(m,[5,5]);%filtering using Weiner filter
bw=im2bw(k,level);
bw2=imfill(bw,'holes');
bw3 = bwareaopen(bw2,5000);
labeled = bwlabel(bw3,8);
cc=bwconncomp(bw3);
Densityoftraffic = cc.NumObjects/(size(bw3,1)*size(bw3,2));
blobMeasurements = regionprops(labeled,'all');
numberofcars = size(blobMeasurements, 1);
subplot(2,2,4) , imagesc(labeled), title (['Foreground']);
hold off;
disp(numberofcars);% display number of cars
disp(Densityoftraffic);%display number of vehiclesJeje Ahmadhttps://uk.mathworks.com/matlabcentral/profile/authors/19993623tag:uk.mathworks.com,2005:Question/6272682020-10-27T05:38:59Z2020-10-27T08:43:35ZBisection Method Error - Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.I'm trying to Run this Below Code with the use of bracketf.m,bisectf.m,makereturn.m and retrisk1.m files. But I am getting this error.Please help me finding the error
Code Trying to Run
rtns=makereturns(20,2);
global rbar; global Q; rbar = mean(rtns); Q = cov(rtns);
global Va; global rho; Va = 0.2; rho =100; x=0.9; d = 0.05;
[a,b] = bracketf(@retrisk1,x,d);
[x,fmin,itns,fns] = bisectf(@retrisk1,a,b,1.0E-4);
x_and_fmin = [x fmin];
iterations_and_function_calls = [itns fns];
y = [x ; 1-x]; invested_fractions = y;
expected_portfolio_return = rbar.*y;
portfolio_risk = y.*Q*y;
Bisectf.m
function [x,fmin,itns,fns] = bisectf(ff,a,b,tol)
v(1) = a;
v(5) = b;
v(3) = (a+b)/2;
f(1) = feval(ff,a);
f(5) = feval(ff,b);
f(3) = feval(ff,v(3));
itns =0; fns = 3;
while abs(v(1)-v(5)) > tol
v(2) = (v(1)+v(3))/2; v(4) = (v(3)+v(5))/2;
f(2) = feval(ff,v(2)); f(4) = feval(ff,v(4));
itns = itns + 1; fns = fns+2;
if f(1) <= f(2) | f(2) <= f(3)
v(5) = v(3); f(5) = f(3);
v(3) = v(2); f(3) = f(2);
else
if f(3) <= f(2) & f(3) <=f(4)
v(1) = v(2); f(1) = f(2);
v(5) = v(4); f(5) = f(4);
else
if f(4) <= f(3) | f(5) <= f(4)
v(1) = v(3); f(1) = f(3);
v(3) = v(4); f(3) = f(4);
end
end
end
end
x = (v(1)+v(5))/2; fmin=feval(ff,x);
Error
> MainCodeToRun
Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.
Error in bisectf (line 5)
f(1) = feval(ff,a);
Error in MainCodeToRun (line 5)
[x,fmin,itns,fns] = bisectf(@retrisk1,a,b,1.0E-4);
bracketm.f
function [a,b,itns,fns] = bracketf(f,x,d)
a = x-d; b = x+d;
fa = feval(f,a); fb= feval(f,b); fx = feval(f,x);
itns = 0; fns = 3;
if fa < fx
while fa < fx & itns <100
b = x; fb = fx;
x = a; fx = fa;
a = x-d; fa = feval(f,a);
itns = itns + 1; fns = fns + 1; d=1.1*d;
end
else
if fb < fx
while fb < fx & itns < 100
a = x; fa = fx;
x = b; fx = fb;
b = x+d; fb = feval(f,b);
itns = itns + 1; fns = fns + 1; d=1.1*d;
end
end
end
if itns == 100
disp('Function may be unbounded below')
end
makereturns.m
function [rtns,graph] = makereturns(m,n)
prices(1,1:n) = 1; rand('state',0); randn('state',0);
noise = 0.005*randn(m+1,n); events = 0.01*(rand(m+1,n)-0.475);
for k = 2:m+1
for j = 1:n
prices(k,j) = prices(k-1,j) *(1+events(k-1,j)+noise(k-1,j));
end
end
for k = 1:m
times(k) = k;
for j = 1:n
rtns(k,j) = 100*(prices(k+1,j) - prices(k,j))/prices(k,j);
end
end
if nargout > 1 & n <= 4
if n==1
plot(times,prices(1:m,1),'k-'); legend(' Asset 1'); end
if n==2
plot(times,prices(1:m,1),'k-',times,prices(1:m,2),'k:');
legend(' Asset 1','Asset 2'); end
if n==3
plot(times,prices(1:m,1),'k-',times,prices(1:m,2),'k:',...
times,prices(1:m,3),'k-.')
legend(' Asset 1','Asset 2','Asset 3'); end
if n==4
plot(times,prices(1:m,1),'k-',times,prices(1:m,2),'k:',...
times,prices(1:m,3),'k-.', times,prices(1:m,4),'k--')
legend(' Asset 1','Asset 2','Asset 3', 'Asset 4'); end
end
retrisk1.m
function [f,g,h] = retrisk1(x)
global Q; global rbar; global rho; global Va
a = [0;1]; B = [1;-1];
V = a.*Q*a + 2*a.*Q*B*x + B.*Q*B*x^2;
R = rbar.*a + rbar.*B*x; P = (V/Va-1).^2;
f = -R + rho*P;
if nargout > 1
dV = 2*a.*Q*B + 2*B.*Q*B*x;
dR = rbar.*B; dP = 2*(V/Va-1)*dV/Va;
g = -dR + rho*dP;
end
if nargout > 2
d2V = 2*B.*Q*B;
d2R = 0; d2P = 2*dV*dV/Va^2 + 2*(V/Va-1)*d2V/Va;
h = -d2R + rho*d2P;
endAbin Punnilethu Bijuhttps://uk.mathworks.com/matlabcentral/profile/authors/20120127tag:uk.mathworks.com,2005:Question/6211782020-10-21T11:26:48Z2020-10-27T08:40:23ZHow to remove an apple twig from binary image?Good day,
I want to determine the diameter of an apple. The only problem is we don't know how to exclude the twig of the apple.K Vermeulenhttps://uk.mathworks.com/matlabcentral/profile/authors/19424888tag:uk.mathworks.com,2005:Question/6273932020-10-27T08:02:07Z2020-10-27T08:39:58ZHow to create 2x2 array containing elements?Create a 2x2 cell array, C which contains the following information:
In element {1,1}, insert the expression below:
my cell
In element {1,2}, insert the array below:
[9 0 3; 2 5 6; 7 81 6]
In element {2,1}, insert the complex number below:
3 + 6i
In element {2,2}, insert the array:
[1 4; 6 7; 11 3]Liam Bouchereauhttps://uk.mathworks.com/matlabcentral/profile/authors/19087180