https://nl.mathworks.com/matlabcentral/answers/questionsMATLAB Answers — New Questions2020-04-08T09:49:58Ztag:nl.mathworks.com,2005:Question/4877222019-10-27T22:09:44Z2020-04-08T09:49:58ZLetters from Answer Key to Percentage?The answer key is:
D B C B A C B D D B B A B B A D C % this from G2:W2 in an Excel Spreadsheet
While (for example), Student 1's answers are:
A A B C C B A B A B B A B B A B B % this is from G3:W3 in an Excel Spreadsheet
How do I convert the student's answers to a percentage based on their answers vs the answer key?
What I have so far is:
multAns = cell2mat(txt4); % txt4 was the student's answer
ansKey = cell2mat(txt1); % txt1 was the answer key
multipleChoiceScore = scoreMult./ansKey;
Any help would be appreciated. Thank you very much!Anne Nguyenhttps://nl.mathworks.com/matlabcentral/profile/authors/16054243-anne-nguyentag:nl.mathworks.com,2005:Question/3599492017-10-06T07:57:40Z2020-04-08T09:49:42ZHow do I interpolate data with non-unique points without loosing information about the curve shape?I have encountered "Error using griddedInterpolant:The grid vectors must contain unique points." when interpolating my 1-D data using interp1 (see below, non-unique data highlighted by arrow). I have not found a solution how to interpolate and at the same time keep the shape of the segmented curve which is crucial for following analysis. Function unique and <https://se.mathworks.com/matlabcentral/fileexchange/8354-consolidator consolidator> change the data. Anyone can help?
<</matlabcentral/answers/uploaded_files/90077/Capture.JPG>>
Janullikhttps://nl.mathworks.com/matlabcentral/profile/authors/4500556-janulliktag:nl.mathworks.com,2005:Question/5161242020-04-07T17:35:43Z2020-04-08T09:49:32ZIF not working with vectorHello, sorry for the trivial question.
I wrote this function:
function f = g(m)
%piecewise function evaluation
if m <= 0
f(n) = -2*m;
else
f(n) = 2*m;
end
end
Which actually works when g is given numbers individually
g(2) = 2, g(-2) = 2
However when I try to plot it by evaluting the function g in an array of value in x created with linspace it seems to "forget" about if condition in the function statement.
x = linspace(-1,1);
g(x) = "gives a straight line 2x, instead of behaving like abs(2x)"Alessandro Cabodihttps://nl.mathworks.com/matlabcentral/profile/authors/17516854-alessandro-caboditag:nl.mathworks.com,2005:Question/5162722020-04-08T08:05:14Z2020-04-08T09:49:32ZHow to raise a decimal numbers as power of A??Hello everyone..I am trying to raise decimal values which is ranging from(0.1:0.01:1) to the power of A(3x3 matrix).(eg.. A^[0.1:0.01:1]). I cannot find my answer anywhere.can anyone help me out..Thanks in advance..Sabari Ghttps://nl.mathworks.com/matlabcentral/profile/authors/14641133-sabari-gtag:nl.mathworks.com,2005:Question/5160922020-04-07T15:39:25Z2020-04-08T09:47:51ZStopFcn not working with audioplayer objectI'm using App Designer with the following code:
app.Player = audioplayer(y, Fs);
app.Player.StopFcn = @PlayerStoppedFcn;
function PlayerStoppedFcn(audioplayer, ~)
% do something
end
However, this error appears regarding the StopFcn callback...
Warning: Error occurred while executing the listener callback for event Custom defined for class asyncio.Channel:
Error using internal.Callback.execute (line 128)
Undefined function 'PlayerStoppedFcn' for input arguments of type 'audioplayer'.
> In asyncio.Channel/onCustomEvent (line 473)
In asyncio.Channel>@(source,data)obj.onCustomEvent(data.Type,data.Data) (line 405)
Can you help? Thanks in advance.John Disandolohttps://nl.mathworks.com/matlabcentral/profile/authors/15963540-john-disandolotag:nl.mathworks.com,2005:Question/5162942020-04-08T09:46:47Z2020-04-08T09:46:47ZProblems with double loopingI am trying to implement this double loop. There is lot of material online on double looping in matlab but I don't manage to make it work.
This is my code:
debt = nan(49,1)
for j = -(6:12)
for i = 2:8
debt(j, i) = ((1 + 0.93) - (1 + j)) + 134.77 + (i - 3.3)
end
end
I would like to be able to save debt accounting for the 7x7 outcomes that the loop produced.
What's wrong with my loop?
Thanks
Armando MAROZZIhttps://nl.mathworks.com/matlabcentral/profile/authors/17653517-armando-marozzitag:nl.mathworks.com,2005:Question/5162932020-04-08T09:45:13Z2020-04-08T09:45:13ZSolving an Improper IntegralHello,
I've tried to solve the following integral as such:
syms x;
f = 1/(sqrt(exp(x)-x))
A = int(f, 1, inf)
and the answer was the function itself:
int(1/(exp(x) - x)^(1/2), x, 1, Inf)
Did I make an error because why is the answer not coming out? The answer is supposed to be 2/sqrt(e).
Thank you.Ahmad El Karihttps://nl.mathworks.com/matlabcentral/profile/authors/18056831-ahmad-el-karitag:nl.mathworks.com,2005:Question/5162882020-04-08T09:21:58Z2020-04-08T09:44:36Zgenerate random number from a function that serves as PDF ?Hello! I have mean zero second order gaussian distribution model and I want to generate random variables from this distribution within a specific interval [ -pi/2, pi/2 ]. the PDF depends on 4 parameters that are 2 variances and 2 other coefficients for the seocnd order. I built the PDF within a mtlab function and I would like to know how can I generate random numbers from this PDF ??
ThanksHakim Jemaahttps://nl.mathworks.com/matlabcentral/profile/authors/17589419-hakim-jemaatag:nl.mathworks.com,2005:Question/4825172019-09-27T17:42:57Z2020-04-08T09:42:11ZHow to download file in Online Matlab?I need help downloading a script in my computure using the online MATLAB. Jose Carrasco Ramonhttps://nl.mathworks.com/matlabcentral/profile/authors/16070496-jose-carrasco-ramontag:nl.mathworks.com,2005:Question/5162102020-04-08T00:02:45Z2020-04-08T09:41:48ZApply function row-wise on a tall arrayHi,
I have a tall array T with some variables, let's say A, B and C. I also have a function f(a,b,c), that only works with scalars a, b and c and cannot be vectorized.
Now I would like to run this function on every row of the tall array yielding a column D.
I tried something like:
% Fill D with nans.
nanLike = @(in) nan(size(in),'like',in);
T.D = matlab.tall.transform(nanLike, T.A);
% Iterate through rows and overwrite nan with function value.
for i = 1:gather(size(T,1))
a = T.A(i);
b = T.B(i);
c = T.C(i);
[a,b,c] = gather(a,b,c);
T.D(i) = f(a,b,c);
end
But that neither works, nor can be efficient.
Do you have any idea?
Here is my real function f just that you see, that it cannot be vectorized so easily (of course, if you can help my vectorize it, the problem would also be solved):
function [opprice] = opprice(S, K, r, TtM, sigma, d, Type, ExerciseType, steps, inputcheck)
%OPPRICE calculates the price of a stock option given the specified
%parameters using BS for European and CRR for American options.
% S: stock price
% K: strike price
% r: risk-free rate
% TtM: time to Maturity in years
% sigma: volatility, (0, inf)
% d: dividend yield, [0, inf)
% Type: {'C', 'P'}
% ExerciseType: {'A', 'E'}
% steps: height of the binomial tree
% inputcheck: if input validity should be checked {true, false}
%% Input Validity Check.
if nargin <= 9
inputcheck = true;
end
if inputcheck == true
if nargin < 9
error('Not enough inputs specified.');
end
if numel(S)~= 1 || ~isnumeric(S) || isnan(S) || S <= 0
opprice = NaN;
return;
end
if numel(K)~= 1 || ~isnumeric(K) || isnan(K) || K <= 0
opprice = NaN;
return;
end
if numel(r)~= 1 || ~isnumeric(r) || isnan(r)
opprice = NaN;
return;
end
if numel(TtM)~= 1 || ~isnumeric(TtM) || isnan(TtM) || TtM <= 0
opprice = NaN;
return;
end
if numel(sigma)~= 1 || ~isnumeric(sigma) || isnan(sigma) || sigma <= 0
opprice = NaN;
return;
end
if numel(d)~= 1 || ~isnumeric(d) || isnan(d) || d < 0
opprice = NaN;
return;
end
if ~any([strcmp(Type,'P'), strcmp(Type,'C')])
opprice = NaN;
return;
end
if ~any([strcmp(ExerciseType,'A'), strcmp(ExerciseType,'E')])
opprice = NaN;
return;
end
if strcmp(ExerciseType,'A')
if steps < 1 || floor(steps) ~= steps
opprice = NaN;
return;
end
end
end
%% Do Pricing.
switch ExerciseType
case {'American', 'A'}
% Precalculate components.
dT = TtM ./ steps;
u = exp(sigma .* sqrt(dT));
p0 = (u.*exp(-d .* dT) - exp(-r .* dT)) ./ (u.^2 - 1);
p1 = exp(-r .* dT) - p0;
% Stock prices at time T.
S_T = S.*u.^(2*(0:steps)'-steps);
% Option type related binomial calculations.
switch Type
case {'Call','C'}
% Option prices at time T.
p = max(S_T - K, 0);
% Move from latest to earliest node.
for j = steps:-1:1
% Binomial value.
p = p0 * p(2:j+1) + p1 * p(1:j);
% Exercise value.
exercise_value = S.*u.^(2*(0:(j-1))'-(j-1)) - K;
p = max(p, exercise_value);
end
case {'Put','P'}
% Option prices at time T.
p = max(K - S_T, 0);
% Move from latest to earliest node.
for j = steps:-1:1
% Binomial value.
p = p0 * p(2:j+1) + p1 * p(1:j);
% Exercise value.
exercise_value = K - S.*u.^(2*(0:(j-1))'-(j-1));
p = max(p, exercise_value);
end
end
% Get price today from tree
opprice = p(1);
case {'European', 'E'}
divisor = sigma * sqrt(TtM);
d_1 = (log(S/K) + (r - d ...
+ sigma^2/2) * TtM) / divisor;
d_2 = d_1 - divisor;
switch Type
case {'Call','C'}
opprice = exp(-d*TtM) * S * normcdf(d_1) ...
- exp(-r*TtM) * K * normcdf(d_2);
case {'Put','P'}
opprice = exp(-r*TtM) * K * normcdf(-d_2) ...
- exp(-d*TtM) * S * normcdf(-d_1);
end
end
endClemens Gerschhttps://nl.mathworks.com/matlabcentral/profile/authors/13861321-clemens-gerschtag:nl.mathworks.com,2005:Question/5162922020-04-08T09:38:30Z2020-04-08T09:39:08Zhow can i simplify this expressionu is 37x37x37x37 complex matrix
h is 37*37 complex matrix
i want to simplify this expression:
N=37;
res=zeros(N,N,N,N);
for i=1:N
for j=1:N
res(:,:,i,j)=h(i,j)*u(:,:,i,j);
end
end
res=sum(res,[3 4]);Dror Aizikhttps://nl.mathworks.com/matlabcentral/profile/authors/12723668-dror-aiziktag:nl.mathworks.com,2005:Question/5159922020-04-07T10:13:05Z2020-04-08T09:38:41ZHow do I find the function corresponding to a graph image?Dear MATLAB community,
I am trying to find the mathematical function corresponding to the following green curve (although I would be most thankful for suggestions for the blue one also). Unfortunately, I don't have the underlying data with which it was created. Can anyone help?
Thanks a lot in advance!
Karam Chehadehttps://nl.mathworks.com/matlabcentral/profile/authors/17469215-karam-chehadetag:nl.mathworks.com,2005:Question/5162912020-04-08T09:37:35Z2020-04-08T09:37:35Znarrowing down data restrictionHi all,
I am setting a restriction to sample the outlier data.
Three restrictions that i have set are:
zscore above 3
W(idx) above 15
three consecutive W(idx) having same value.
Values that meet all three resitrictions shall be classified as outliers.
idx is the time variable and the W is the result.
I came up with this equation, but the result of what i wish to get is only upto the second restriction right.
please help me out how to restructure the last restriction correctly.
Thanks all.
stdDev = std(W(idx))
meanValue = mean(W(idx))
zFactor = 3
outliers = find((abs(W(idx)-meanValue) > (zFactor * stdDev)) & (W(idx) > 15) & (W(idx) == W(idx-1) == W(idx-2) == (W(idx-3))))Sehoon Changhttps://nl.mathworks.com/matlabcentral/profile/authors/7980157-sehoon-changtag:nl.mathworks.com,2005:Question/5162902020-04-08T09:32:09Z2020-04-08T09:34:42ZResults does not show in array form (bandpass)I have 2 codes here for me to substitute into a formula (Bandpass formula), my expected results would be individual of x(-2), x(-1), x(1), x(2), however, I would end up getting a complete summation value based on it. I found out it was due to the denominator (n) which I am currently now stuck in.
a) my result : hn = - 0.0332 (INCORRECT)
b) my results: hn = [- 0.0887 0.0117 0.0117 - 0.0887] (PARTIALLY CORRECT) however, the '0.0887' shall be divided by 2 due to the 'n1' situate in the denominator of the hn equation.
% Simulation for (a)
fs = 8000;
fL = 1600; %lower cutt off freq
fH = 1800; %upper cutt off freq
N = 5; %numbers of taps
n = (N-1)/2;
n1 = -n:1:n; %-2 to 2 for x-axis
n1(ceil(length(n1)/2)) = []; % Removal of 0
wcL = (2*pi*fL/fs); % normalize lower fc
wcH = (2*pi*fH/fs); % normalize upper fc
%__BANDPASS__
hn0 = (wcH-wcL)/pi; %when n=0
hn = abs((sin(wcH*n1))/(n1*pi))- abs(sin(wcL*(n1))/(n1*pi)); %when n not 0 and n=1, n=2
%Simulation for (b)
fs = 8000;
fL = 1600; %lower cutt off freq
fH = 1800; %upper cutt off freq
N = 5; %numbers of taps
n = (N-1)/2;
n1 = -n:1:n; %-2 to 2 for x-axis
n1(ceil(length(n1)/2)) = []; % Removal of 0
wcL = (2*pi*fL/fs); % normalize lower fc
wcH = (2*pi*fH/fs); % normalize upper fc
%__BANDPASS__
hn0 = (wcH-wcL)/pi; %when n=0
hn = abs((sin(wcH*n1))/(pi))- abs(sin(wcL*(n1))/(pi)); %when n not 0 and n=1, n=2
Darren Fonghttps://nl.mathworks.com/matlabcentral/profile/authors/14699130-darren-fongtag:nl.mathworks.com,2005:Question/5128782020-03-25T14:39:16Z2020-04-08T09:34:33ZOptimoptions error: "Empty keys are not allowed in this container" (no number given)What is the source of my error? I am running a program that calls optimoptions with the following command:
options = optimoptions(@fmincon,'Algorithm','sqp');
This results in the following errors:
Error using optimoptions (line 124)
Empty keys are not allowed in this container.
Error in Cure_main (line 36)
options = optimoptions(@fmincon,'Algorithm','sqp');
Cure_main.m is my main function. Prior to line 36, no other functions are yet called. Other members of my team can run the code, using copies of my files. They are using 2018a, I am using a newly installed copy of 2020a. I have confirmed that I can open optimoptions in my copy of matlab.
I have also checked that I have the appropriate toolbox:
>> license('inuse')
matlab
optimization_toolbox
I have not changed the path for anything in my matlab, other than adding the directory of my script files and the .txt that they use. I have tried changing @fmincon to 'fmincon', and had the same result.
The complete code is:
clc; clear all; close all;
format long;
global Atest T m;
d=load('1.txt');
m=1580;
Atest=d(:,2)*1.0;
T=d(:,1);
x=[
0.0106777326336
];
% I have removed a large number of commented-out value options here
options = optimoptions(@fmincon,'Algorithm','sqp');
There is more after this, but it is not necessary to reproduce the error.
Geoffrey Rivershttps://nl.mathworks.com/matlabcentral/profile/authors/17875485-geoffrey-riverstag:nl.mathworks.com,2005:Question/5162732020-04-08T08:07:43Z2020-04-08T09:33:52ZUndefined function 'equation' for input arguments of type 'double'I want to write a function equation(M,epsilon,tol) which sets the solution of with an approximation error . So I have:
function x=newtonp(f, x, tol, h)
if nargin<4
h=1e-8
end
if nargin<3
tol=1e-8
end
while abs(f(x))>tol
g=(f(x+h)-f(x))/h
x=x-f(x)/g
end
end
function y=equation(M,epsilon,tol)
y=M+epsilon*sin(x)-x
end
Then I write:
newtonp(@equation(x),x, tol, h)
However I get
Undefined function 'equation' for input arguments of type 'double'
Can anyone correct my code?xtz xtzhttps://nl.mathworks.com/matlabcentral/profile/authors/18095660-xtz-xtztag:nl.mathworks.com,2005:Question/5161952020-04-07T22:08:48Z2020-04-08T09:31:49ZInput function must return 'double' or 'single' values. Found 'sym'. dear all
when i using integral command although i define z i get the following error
clc
clear all
E2=10;
E1=20;
lE=E2/E1;
n=1;
h=2;
v1=30;
v2=40;
lv=v2/v1;
sym z
Eb=1+(((2*z+h)/2*h)^n)*(lE-1)
vb=1+(((2*z+h)/2*h)^n)*(lv-1)
fun=@(z) Eb/((1-(v1^2)*(vb^2))*h)
A11=integral(fun,-1/2,1/2)
and the error :
Undefined function or variable 'z'.
Error in first (line 13)
Eb=1+(((2*z+h)/2*h)^n)*(lE-1)
and also when i use syms z instead of sym z i get the following one :
fun =
function_handle with value:
@(z)Eb/((1-(v1^2)*(vb^2))*h)
Error using integralCalc/finalInputChecks (line 511)
Input function must return 'double' or 'single' values. Found 'sym'.
Error in integralCalc/iterateScalarValued (line 315)
finalInputChecks(x,fx);
Error in integralCalc/vadapt (line 132)
[q,errbnd] = iterateScalarValued(u,tinterval,pathlen);
Error in integralCalc (line 75)
[q,errbnd] = vadapt(@AtoBInvTransform,interval);
Error in integral (line 88)
Q = integralCalc(fun,a,b,opstruct);
Error in first (line 18)
A11=integral(fun,-1/2,1/2)
i really appreciated if someone could help me with this shahin hashemihttps://nl.mathworks.com/matlabcentral/profile/authors/11613864-shahin-hashemitag:nl.mathworks.com,2005:Question/5129032020-03-25T16:04:06Z2020-04-08T09:31:34Zcrop multiple images with freehandhi every body. i want to crop multiple images with freehand , and i have written the code below, but i have this eror
Error in Untitled2 (line 19)
I = imcrop(I,BW) ; % crop image
could any body help me please?
images = dir('E:\phd\zahra taati\matlabprozhe\50%\ct50.0% - Copy\*.jpg'); % GEt all images of the folder
N = length(images) ; % number o fimages
I = imread(images(1).name) ;
h_im = imshow(I);
e = imfreehand ;
BW = createMask(e,h_im)
BW(:,:,2) = BW;
BW(:,:,3) = BW(:,:,1);
ROI = I;
ROI(BW == 0) = 0;
figure, imshow(ROI);
for i = 1:N
I = imread(images(i).name) ; % REad image
I = imcrop(I,BW) ; % crop image
[filepath,name,ext] = fileparts(images(i).name) ;
imwrite(I,strcat(name,'cropped',ext)) ; % Save image
endtalayeh ghodsihttps://nl.mathworks.com/matlabcentral/profile/authors/14229557-talayeh-ghodsitag:nl.mathworks.com,2005:Question/4779772019-08-28T19:52:54Z2020-04-08T09:29:36ZDoes Matlab C/C++ Graphics Library for compiler 2.0/3.0, support mix language (.c, .m) ? Runtime error when tried to generate a stand alone executable, when combining Matlab module with graphics and .c routine.
Amazingly the the following compile command did generate an executable but it did not include the graphics library call as part of the run time.
I used the following command to get the executable:
mcc -B sgl -t -W lib:Pkgout <Main.m> <module1.m> <module2.c>
And I get the fololowing error when I ran Main.exe
error. function call "figure" requires graphics library , use "-B sgl" switch when compiling
-----------------------------------------------------------------------------------------------
I tried various combination of the mcc command but no luck.
Matalb R11, R13Siamak Mohebbihttps://nl.mathworks.com/matlabcentral/profile/authors/105759-siamak-mohebbitag:nl.mathworks.com,2005:Question/5162892020-04-08T09:26:02Z2020-04-08T09:26:02ZMultcompare on repeated measure ANOVA object performs double two way comparisonsDear all,
I ran a repeated measure two way ANOVA with a 2 by 4 fully within design. Here is an example of the code I ran:
% generate random data for the example
rndData = randn(24,8);
% Create a table storing the respones
varNames = {'Y1','Y2','Y3','Y4','Y5','Y6','Y7','Y8'};
t = array2table(rndData,'VariableNames',varNames);
% Create a table reflecting the within subject factors 'TestCond', 'Attention', and 'TMS' and their levels
factorNames = {'Cate','Task'};
within = table({'A'; 'A'; 'B'; 'B'; 'C'; 'C'; 'D'; 'D'},{'I';'II';'I';'II';'I';'II';'I';'II'},'VariableNames',factorNames);
% fit the repeated measures model
rm = fitrm(t,'Y1-Y8~1','WithinDesign',within);
% run my repeated measures anova here
[ranovatbl] = ranova(rm, 'WithinModel','Cate*Task');
% make pairwise comparisons for the two-way interactions
%
% see: help RepeatedMeasuresModel/multcompare
multcompare(rm,'Task','By','Cate')
The above multcompare yields the following:
Cate Task_1 Task_2 Difference StdErr pValue Lower Upper
____ ______ ______ __________ _______ ________ _________ ________
'A' 'I' 'II' -0.030251 0.28824 0.91732 -0.62652 0.56602
'A' 'II' 'I' 0.030251 0.28824 0.91732 -0.56602 0.62652
'B' 'I' 'II' -0.09305 0.25671 0.72031 -0.62409 0.43799
'B' 'II' 'I' 0.09305 0.25671 0.72031 -0.43799 0.62409
'C' 'I' 'II' -0.33807 0.34831 0.34184 -1.0586 0.38246
'C' 'II' 'I' 0.33807 0.34831 0.34184 -0.38246 1.0586
'D' 'I' 'II' 0.44612 0.24336 0.079751 -0.057304 0.94955
'D' 'II' 'I' -0.44612 0.24336 0.079751 -0.94955 0.057304
I am a bit confused by the fact that within each 'cate', we perform the following test: I vs II and then II vs I. Both are statisticaly the same, one simply yields the negative of the other. The multcompare corrects for multiple comparison problem paused by such methods, but my worry is that if the multcompare corrects for all the tests displayed here, the correction will actually be exagerated, as only half of the tests are necessary.
Thanks in advance for your support,
Kind regards
Alex Lepauvrehttps://nl.mathworks.com/matlabcentral/profile/authors/16039918-alex-lepauvretag:nl.mathworks.com,2005:Question/5161132020-04-07T16:29:40Z2020-04-08T09:25:26ZOde45, evolution giving NaNs after some time, with no evidence of singularities in the equationsHello,
Attached is a simple integrator for four coupled first order ode s.
after a certain time, the 4-vector solution turns into NaNs with no evidence of singularities in the equations.
This happens after a certain range where the solutions (starting as real) are written in complex notation although the imaginary part is zero. (why?)
can anyone please have a look and let me know if there's something im missing?Mohammad Farhathttps://nl.mathworks.com/matlabcentral/profile/authors/13722959-mohammad-farhattag:nl.mathworks.com,2005:Question/5162042020-04-07T23:33:25Z2020-04-08T09:23:21ZNeed help with mvregressHello all,
I am new to matlab. I am trying to estimate the coefficients of my linear regression:
Ypca = A + B ∙ X + Epca
I have the table Ypca which is 15*3884 table and table X which is 7769*2 table.
I used the following code:
[beta,Sigma] = mvregress(X,Y,'algorithm','cwls');
My goal is to find out A, B and Epca.
But the error that I am getting is as follows:
Can someone please tell me how to proceed with this error? Thank you.Swetha Kallahttps://nl.mathworks.com/matlabcentral/profile/authors/15881052-swetha-kallatag:nl.mathworks.com,2005:Question/5162802020-04-08T08:42:13Z2020-04-08T09:22:37ZWhy does my function output a series of answers that I don't want and have tried my best to supressMy code is as follows
function [T,Q]=osc_2
tspan = [0: pi/20: 2*pi];
qinit_1=[1;0];
qinit_2=[0;1];
[T,Q] = ode45(@osc,tspan,qinit_1);
phi_1=[Q((end), 1); Q((end), 2)];
[T,Q] = ode45(@osc,tspan,qinit_2);
phi_2=[Q((end), 1); Q((end), 2)];
eigenvalues=eig([phi_1,phi_2]);
Stability=eigenvalues(1,1)*eigenvalues(2,1)
end
with an accompanying second piece of code
function dqdt = osc(t,q)
dqdt = zeros(2,1);
a1=0;
a2=2;
a3=1;
dqdt(1) = q(2);
dqdt(2) = -a1*q(2)-q(1)*(a2+a3*cos(t));
end
When I run the first function, it returns the stability as I want it to, but it also outputs the following
ans =
0
0.1571
0.3142
0.4712
0.6283
0.7854
0.9425
1.0996
1.2566
1.4137
1.5708
1.7279
1.8850
2.0420
2.1991
2.3562
2.5133
2.6704
2.8274
2.9845
3.1416
3.2987
3.4558
3.6128
3.7699
3.9270
4.0841
4.2412
4.3982
4.5553
4.7124
4.8695
5.0265
5.1836
5.3407
5.4978
5.6549
5.8119
5.9690
6.1261
6.2832
Apologies for the length of the post, but is it possible to prevent the ans output from coming up? as far as I can tell it's simply giving the range of values used in tspan but I can't work out why it isn't supressed by the semicolon on that line.
I am very much new to MATLAB so simpler answers would be strongly prefered. I am also aware that there is most likely a different way of doing this as I only require the Q(end) values, however, this is the best I could do.Kieran Corriganhttps://nl.mathworks.com/matlabcentral/profile/authors/17851995-kieran-corrigantag:nl.mathworks.com,2005:Question/5162872020-04-08T09:21:55Z2020-04-08T09:21:55ZHow to use simscape electrical with student licenseI bought the MATLAB and Simulink Student Suite license for my couse purposes
After installation I realized that I need the Simscape Electrical, which isn't included in my package
So I bought the Simscape and Simscape Electrical separately
But now it gives the message "license for Simscape Electrical is not available."
I tried the license('test','Power_System_Blocks') command and it gives me 0
How can I fix this?Ivy Averinahttps://nl.mathworks.com/matlabcentral/profile/authors/12770784-ivy-averinatag:nl.mathworks.com,2005:Question/5161372020-04-07T18:22:38Z2020-04-08T09:21:24Z"Failure in initial objective function evaluation" Hello everybody,
I'm trying to set up a optimization. As a function for the optimization I want to use a Class I wrote with a bunch of calculations. The class itself is working as it should. But when I try to run the fmincon solver I get an error warning: "Failure in initial objective function evaluation. FMINCON cannot continue"
I think I'm calling the method from the Class in the wrong way, wherever my attempts to change the way I call it didn't work either. Has anybody some advice?
%Instanz erstellen
myHoltropObject = Holtrop_R_T(12.86, 900);
x0 = [50 12 3.2 -4.5];
lb = [40 10 3 -5];
ub = [60 15 5 5];
gs = GlobalSearch;
options = optimoptions('fmincon','Algorithm', 'interior-point',...
'UseParallel',true, 'Display','off','MaxFunctionEvaluations',6000, 'TolCon', 1e-4, 'TolFun', 1e-4);
objectiveA = @(in) calcRT(in);
constraintA = @(in) RT_equal84(in, calcRT);
problem = createOptimProblem('fmincon', ...
'objective',objectiveA, ...
'x0',x0, ...
'lb',lb, ...
'ub',ub, ...
'nonlcon',constraintA, ...
'options',options)
% Run optim search
%[resultVector,~,exitFlag,~,~] = run(gs,problem); % this is for global optimization
[resultVector,~,exitFlag,~,~,~,~] = fmincon(problem) % this is for local search of optimum
% ERROR:
problem =
objective: @(in)calcRT(in)
x0: [50 12 3.2000 -4.5000]
Aineq: []
bineq: []
Aeq: []
beq: []
lb: [40 10 3 -5]
ub: [60 15 5 5]
nonlcon: @(in)RT_equal84(in,calcRT)
solver: 'fmincon'
options: [1×1 optim.options.Fmincon]
Unable to resolve the name myHoltropObject.getR_T.
Error in User>calcRT (line 31)
RT = myHoltropObject.getR_T([Lwl B T lcb]);
Error in User (line 10)
objectiveA = @(in) calcRT(in);
Error in fmincon (line 552)
initVals.f = feval(funfcn{3},X,varargin{:});
Caused by:
Failure in initial objective function evaluation. FMINCON cannot continue.
%
%Ergebnisausgabe
fprintf('Optimale Abmessungen: \nLänge: %5.3f \nBreite: %5.3f \nTiefgang: %5.3f \nlcb: %5.3f \n',resultVector(1), resultVector(2), resultVector(3), resultVector(4));
%Objective function
function RT = calcRT(in)
Lwl = in(1);
B = in(2);
T = in(3);
lcb = in(4);
RT = myHoltropObject.getR_T([Lwl B T lcb]);
end
%Constraint function
function [c, ceq] = RT_equal84(in)
RT = calcRT(in);
ceq = RT-616;
c = [];
end
Leon Stolphttps://nl.mathworks.com/matlabcentral/profile/authors/17749366-leon-stolptag:nl.mathworks.com,2005:Question/5162862020-04-08T09:20:33Z2020-04-08T09:21:10ZBinary Search - Descending orderHi! I would like to know how to modify the code below so that it can work for vectors that are sorted in descending order, rather than ascending order. Your function should not sort the vector.
This is the code:
% FILENAME: binsearch-2.m
% SUBMISSION TIME: 08/04/2020 07:13:38 pm
% --- Begin file ---
function [left, right] = binsearch(vec,targetVal,left,right)
% SEARCH Binary search algorithm step.
% [left, right] = BINSEARCH(vec,targetVal,left,right) returns the end points
% produced by one step of the binary search algorithm with
% target value targetVal. The elements of vec must be in ascending order.
% Compute the mid-point by halving the distance between
% the end points and rounding to the nearest integer.
midPt = round((left + right)/2)
if vec(midPt) == targetVal
% targetVal has been found
left = midPt;
right = midPt;
elseif vec(midPt) > targetVal
% targetVal must be before midPt
right = midPt - 1;
else
% targetVal must be after midPt
left = midPt + 1;
endQueenie Chanhttps://nl.mathworks.com/matlabcentral/profile/authors/17894860-queenie-chantag:nl.mathworks.com,2005:Question/5154942020-04-05T10:45:54Z2020-04-08T09:20:12ZPlotting gps coordinates in AppdesignerHello everyone,
I have to plot a map in gps coordinates inside a UIAxes in Appdesigner, but using "geoplot" function the app plots the map in an other image outside the App. I tried give "app.UIAxes3" (which is the graph where I want to plot gps coordinates) as first argument of the function, but Matlab gives error saying that I have to use latitudinal/longitudinal coordinates.
Here is the code, and an image showing the map outside the app, instead i want the map in the UIAxes marked in red
%Function to plot TrackMap
function results = geoplotter(app)
app.track=geoplot([app.lat],[app.lon])
end
Maybe is there another way to write geoplot function in appdesigner or a different functions to read and plot map in gps coordinates?
Many ThanksFrancesco Carrarohttps://nl.mathworks.com/matlabcentral/profile/authors/17494940-francesco-carrarotag:nl.mathworks.com,2005:Question/5162852020-04-08T09:19:12Z2020-04-08T09:19:12ZError in port widths or dimensions. ' SFunction ' in simulinkI am trying to execute the simulation with my model in Simulink and I got this only error:
"Error in port widths or dimensions. Invalid dimension has been specified for input ' SFunction ' "
But I haven't used any S-Function block. How is it possible?
I follow all the arrows and dimensions match each other and are correct. Any idea of what might be the problem, please?
Thanks!!Clara Sansalvadohttps://nl.mathworks.com/matlabcentral/profile/authors/10301991-clara-sansalvadotag:nl.mathworks.com,2005:Question/5162842020-04-08T09:15:43Z2020-04-08T09:15:43ZCompile MEX Function generated by CMakeLists.txtHello,
I compiled a C++ MEX function for Simulink with the help of a CMakeLists.txt, but I have the problem, that I can not compile it with Visual Studio as described in https://de.mathworks.com/matlabcentral/answers/460148-how-can-i-debug-a-mex-file-on-microsoft-windows-platforms-with-microsoft-visual-studio-2017.
The Code is compiled with created with "cmake -G"Visual Studio 14 2015 Win64" -DCMAKE_BUILD_TYPE=Debug .." and build with "cmake --build . --config Debug".
Does someone have an idea what the problem could be, that the resulting .mexw64 is not debuggable with Visual Studio?
The CMakeLists.txt looks like the following:
cmake_minimum_required (VERSION 3.3)
# set(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING INTERNAL FORCE)
set (CMAKE_CXX_STANDARD 11)
SET( CMAKE_CXX_COMPILER mex )
SET( CMAKE_C_COMPILER mex )
project (test_sf_1)
find_package(Matlab REQUIRED COMPONENTS MX_LIBRARY ENG_LIBRARY MEX_COMPILER )
if (WIN32)
if ("${CMAKE_SIZEOF_VOID_P}" STREQUAL "8")
#set(MATLAB_DIR "C:/SW/MATLAB/R2015B" CACHE STRING "MATLAB install directory")
set(TARGET_SUFFIX mexw64)
link_directories(${Matlab_ROOT_DIR}/extern/lib/win64/microsoft)
else ()
#set(MATLAB_DIR "C:/SW/MATLAB/R2015B" CACHE STRING "MATLAB install directory")
set(TARGET_SUFFIX mexw32)
link_directories(${Matlab_ROOT_DIR}/extern/lib/win32/microsoft)
endif ()
elseif (APPLE)
#set(MATLAB_DIR "/Applications/MATLAB_R2018b.app" CACHE STRING "MATLAB install directory")
set(TARGET_SUFFIX mexmaci64)
set (CMAKE_SHARED_LINKER_FLAGS "-Wl,-exported_symbols_list,${MATLAB_DIR}/extern/lib/maci64/mexFunction.map")
else ()
set(TARGET_SUFFIX mexa64)
endif ()
add_library(${PROJECT_NAME} SHARED
test_sf_1.cpp test_sf_1_wrapper.cpp
)
#SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES PREFIX ".${TARGET_SUFFIX}")
if (WIN32)
target_compile_definitions(${PROJECT_NAME} PUBLIC
MATLAB_MEX_FILE
_CRT_SECURE_NO_WARNINGS
"DLL_EXPORT_SYM=__declspec(dllexport)"
)
else ()
target_compile_definitions(${PROJECT_NAME} PUBLIC MATLAB_MEX_FILE)
endif ()
target_include_directories(${PROJECT_NAME} PUBLIC
${Matlab_ROOT_DIR}/extern/include
${Matlab_ROOT_DIR}/simulink/include
include
)
if (WIN32)
target_link_libraries(${PROJECT_NAME} ${Matlab_MX_LIBRARY} ${Matlab_MEX_LIBRARY})
elseif (APPLE)
target_link_libraries(${PROJECT_NAME}
${Matlab_ROOT_DIR}/bin/maci64/libmat.dylib
${Matlab_ROOT_DIR}/bin/maci64/libmex.dylib
${Matlab_ROOT_DIR}/bin/maci64/libmx.dylib
)
endif ()
set_target_properties(${PROJECT_NAME} PROPERTIES SUFFIX ".${TARGET_SUFFIX}")
add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy
"$<TARGET_FILE:${PROJECT_NAME}>"
"${CMAKE_CURRENT_SOURCE_DIR}"
)Florian Böckhttps://nl.mathworks.com/matlabcentral/profile/authors/14284658-florian-bocktag:nl.mathworks.com,2005:Question/5162792020-04-08T08:32:28Z2020-04-08T09:13:38ZFast checking if array has repeated elements or notI need to check whether a given array, A has repeated elements or not and return in true or false. The function runs near about 5*10^6 times. Initially I tried this
function flag = hasNoRepeats(A)
flag = numel(A)==numel(unique(A)) ;
end
This is very slow, it takes about 90-100 seconds. It is given that array has all positive integers and they are in between 1 and K.
function flag = hasNoRepeats(A,K)
tmp = zeros(1,K);
flag = true;
for i=1:numel(A)
if tmp(A(i))
flag = false;
break
end
tmp(A(i)) = 1;
end
end
This version is faster (~20 secs) but still slower than my requirements. Is there any way to do it faster?Dhritishmam Sarmahhttps://nl.mathworks.com/matlabcentral/profile/authors/13338075-dhritishmam-sarmahtag:nl.mathworks.com,2005:Question/5162822020-04-08T09:05:43Z2020-04-08T09:12:19ZHow to draw 3d signalI want to draw series of signals like this
Debasish Janahttps://nl.mathworks.com/matlabcentral/profile/authors/10061527-debasish-janatag:nl.mathworks.com,2005:Question/5159562020-04-07T06:40:50Z2020-04-08T09:09:38ZI am trying to create a normal random moving point for each individual point in a 3D scatter point. How do I go about to do this?I am trying to replicate the random movements (gaussian distribution) found in particles and to do that, I have already made a moving plot (in a normal random distribution) but I am trying to have a maybe 5 by 5 number of points with each point having its on random moving point.
Code attached are the moving plot and the scatter plotsui zhi lauhttps://nl.mathworks.com/matlabcentral/profile/authors/18082904-sui-zhi-lautag:nl.mathworks.com,2005:Question/5162252020-04-08T02:19:34Z2020-04-08T09:09:03ZWhat statistical analysis should I use with MATLAB?What statistical analysis should I use with MATLAB to get the optimum combination of X,Y, Cement, and Sand that will yield the highest Compressive Strength? (X and Y are used as partial replacements for cement and sand, respectively)
Jov Nicole Juriahttps://nl.mathworks.com/matlabcentral/profile/authors/11536609-jov-nicole-juriatag:nl.mathworks.com,2005:Question/2198032015-05-27T22:00:37Z2020-04-08T09:08:44ZHow To Smooth The Image Edge<<
<</matlabcentral/answers/uploaded_files/31654/hand_edge.png>>
>>i use :
image=imread('hand.png');
e=edge(image,'canny');
imshow(e);behnam emamihttps://nl.mathworks.com/matlabcentral/profile/authors/6465213-behnam-emamitag:nl.mathworks.com,2005:Question/5162832020-04-08T09:07:37Z2020-04-08T09:07:37ZProduct block in Simulink doesn't work properlyHello to everyone,
I'm having an issue with the "product" block. I'm multiplying a variable with a signal generated by the "compere to zero block". I would expect zero as output from the "product block" when also signal is zero but this doesn't occurs. Blocks and simulation run with the same sample time.
Does anyone know how to fix it?
Thanks,
Paris
Paris Pasqualinhttps://nl.mathworks.com/matlabcentral/profile/authors/11341708-paris-pasqualintag:nl.mathworks.com,2005:Question/5162812020-04-08T09:02:46Z2020-04-08T09:02:46ZHow to calculate the power spectra by the power spectra?Dear Colleagues,
If I have signals A and B, respectively, and how to calculate the power specra of A by the power spectrum of B?
Could you give me some suggestions?
Thank you very much! Kathleenhttps://nl.mathworks.com/matlabcentral/profile/authors/1669344-kathleentag:nl.mathworks.com,2005:Question/2708952016-03-01T21:27:44Z2020-04-08T08:59:36ZArduino Simulink Serial Communication<<
<</matlabcentral/answers/uploaded_files/46595/s1.png>>
<</matlabcentral/answers/uploaded_files/46597/s2.png>>
>>
Hi ;
I am using the models above. I am transmitting constant 100 to arduino, but I cannot read 100 on the receive scopes. I uploaded them separately and I also uploaded them in the same model. I couldn't read 100 in both ways. What could be wrong?
Thank you.semih ucarihttps://nl.mathworks.com/matlabcentral/profile/authors/5790878-semih-ucaritag:nl.mathworks.com,2005:Question/5162602020-04-08T06:19:50Z2020-04-08T08:56:55Zarray exceeds maximum array size using dbscan functionHi,
i have a huge data from the radar sensor most likely 2-3 millions of data i.e xy coordinates.
i am using dbscan where pdist2 function is called, due to huge data it says array exceeds maximum size , you can find the same as attahced, can you please do help me out how can i proceed further ?
Please note : i do not want to cut/separate the data.SatyaPrakash Guptahttps://nl.mathworks.com/matlabcentral/profile/authors/16893253-satyaprakash-guptatag:nl.mathworks.com,2005:Question/5162582020-04-08T06:01:03Z2020-04-08T08:56:38ZHow to display only red parts of an image?
The Image above is an output from using the savitky_golay_filter made by Image Analyst. I am working on taking edges out of an image. I need only the red edges I produced from the image, curve fit and find Trajectory.
This is a college project Im working. Would be great if someone could guide me as deadlines shortcoming.
Attached is the image below of how I want my output to be:
I am stuck at part (c). Outline.
Thanks in advace,
~Harshan DesuHarshan Desuhttps://nl.mathworks.com/matlabcentral/profile/authors/15516904-harshan-desutag:nl.mathworks.com,2005:Question/5162022020-04-07T23:28:53Z2020-04-08T08:55:33ZEngineering lab Vector length errorBelow i have the following code. When I try to run it I get an error for figure 3 because it says the vectors are not the same length. New to MATLAB how can I fix or correct this.
syms w1 w2 OC AC theta t
% Define variables w1 to 0.5, w2 to 1.5, OC to 6, AC to 2
w1 = 0.5;
w2 = 1.5;
OC = 6;
AC = 2;
% set theta from 0 to 360 for one rotation
theta = 0:0.1:360;
% set X and Y component of velocity equations at point A w.r.t. theta
Vaox = OC*w1.*cosd(90+theta)+ AC*w2.*cosd(90+3.*theta);
Vaoy = OC*w1.*sind(90+theta)+ AC*w2.*sind(90+3.*theta);
% set X and Y component of acceln equations at point A w.r.t. theta
Aaox = OC*w1^2.*cosd(180+theta) + AC*w2^2.*cosd(180+3.*theta);
Aaoy = OC*w1^2.*sind(180+theta) + AC*w2^2.*sind(180+3.*theta);
% set time from 0 to 12.566 seconds
t = 0:0.1:12.56637;
% set resultant velocity and acceleration equations at point A w.r.t time
Va = sqrt(Vaox.^2 + Vaoy.^2);
Aa = sqrt(Aaox.^2 + Aaoy.^2);
% Jerk equations for x and y components and resultant jerk
Jaox = diff(Aaox);
Jaoy = diff(Aaoy);
Jaor = diff(Aa);
% Position equations for x and y components and resultant position
Paox = cumtrapz(Vaox);
Paoy = cumtrapz(Vaoy);
Paor = cumtrapz(Va);
%plotting
figure;
subplot(1,3,1), plot((theta*(pi()/180))/w1,Paox), xlabel('Time(sec)'), ylabel('X comp. of pos. at A (m)');
subplot(1,3,2), plot((theta*(pi()/180))/w1,Paoy), xlabel('Time(sec)'), ylabel('Y comp. of pos. at A (m)');
subplot(1,3,3), plot((theta*(pi()/180))/w1,Paor), xlabel('Time(sec)'), ylabel('Resultant pos. at A (m)');
figure(2);
subplot(1,4,1), plot((theta*(pi()/180))/w1,2*Paor), xlabel('Time(sec)'), ylabel('(Width 2) Resultant pos. at A (m)');
subplot(1,4,2), plot((theta*(pi()/180))/w1,3*Paor), xlabel('Time(sec)'), ylabel('(Width 3)Resultant pos. at A (m)');
subplot(1,4,3), plot((theta*(pi()/180))/w1,4*Paor), xlabel('Time(sec)'), ylabel('(Width 4)Resultant pos. at A (m)');
subplot(1,4,4), plot((theta*(pi()/180))/w1,5*Paor), xlabel('Time(sec)'), ylabel('(width 5)Resultant pos. at A (m)');
figure(3);
subplot(1,3,1), plot((theta*(pi()/180))/w1,Jaox), xlabel('Time(sec)'), ylabel('X comp. of jerk at A (m/s^3)');
subplot(1,3,2), plot((theta*(pi()/180))/w1,Jaoy), xlabel('Time(sec)'), ylabel('Y comp. of jerk. at A (m/s^3)');
subplot(1,3,3), plot((theta*(pi()/180))/w1,Jaor), xlabel('Time(sec)'), ylabel('Resultant jerk. at A (m/s^3)');Logan Kinghttps://nl.mathworks.com/matlabcentral/profile/authors/18066266-logan-kingtag:nl.mathworks.com,2005:Question/5162402020-04-08T03:28:31Z2020-04-08T08:46:40ZUnexplained error using fitdist with Stable distro - help?I am receiving an unusual error that I can't decode when using fitdist with the 'Stable' distribution option. I've tried troubleshooting by using different datasets and different distributions; the Normal works on the same data. I've used fitdist for stable distributions many times, though not with this release and not in the past 6 months. I've never encountered this error / difficulty before.
The error is:
"Unrecognized function or variable 'getIpOptions'.
Error in fmincon (line 832)
options = getIpOptions(options,sizes.nVar,mEq,flags.constr,defaultopt,10,0.01);
Error in prob.StableDistribution>stablefit (line 1318)
[parmhat,~,err,output] = fmincon(@(params)stable_nloglf(x,params),phi0, ...
Error in prob.StableDistribution.fit (line 211)
params = stablefit(x,0.05,opt);
Error in fitdist>localfit (line 245)
pd = feval(fitter,x,'cens',c,'freq',f,varargin{:});
Error in fitdist (line 192)
pd = localfit(dist,fitter,x,cens,freq,args{:});"
Code that works is:
load hospital;
z = hospital.Weights;
pd = fitdist (z,'Normal');
This generates the error:
pd2 = fitdist(z,'Stable');
Is this a bug in r2020a? I have a copy of Nolan's stablefit toolbox and it fits the same data without throwing an error and with the following result:
>> stablefit(z,1,0)
ans =
2.0000 -0.0214 18.6947 154.0000Chad Bollmannhttps://nl.mathworks.com/matlabcentral/profile/authors/6111580-chad-bollmanntag:nl.mathworks.com,2005:Question/5158852020-04-06T20:55:48Z2020-04-08T08:40:50ZHow to filter a signal(s) open in a UIAXES in matlab app designer?Hi All
I have a listbox from which I choose some signal names and plot them on my UIAXES. now wanted to make a filter button. how could I transfer those signals to the filtering button ?
maybe assuming I have 3 signals already plottedfarzadhttps://nl.mathworks.com/matlabcentral/profile/authors/2231846-farzadtag:nl.mathworks.com,2005:Question/5152512020-04-04T03:59:26Z2020-04-08T08:35:13ZtrainNetwork error unable to read fileHI all,
I am learning to train a convolutional network for image classification on the cloud. As a first step, I am following the example named "Train Network in the Cloud Using Automatic Parallel Support" on Mathworks.
I have started my cluster successfully and uploaded the cifar10 image library to my Amazon S3 bucket.
I then create succssefully the datastore using:
imdsTrain = imageDatastore('s3://mybucket/cifar10/train', ...
'IncludeSubfolders',true, ...
'LabelSource','foldernames');
My problem comes at the training level, where I use:
options = trainingOptions('sgdm', ...
'ExecutionEnvironment','parallel', ... % Turn on automatic parallel support.
'InitialLearnRate',initialLearnRate, ... % Set the initial learning rate.
'MiniBatchSize',miniBatchSize, ... % Set the MiniBatchSize.
'Verbose',true, ... % Do not send command line output.
'Plots','training-progress', ... % Turn on the training progress plot.
'L2Regularization',1e-10, ...
'MaxEpochs',50, ...
'Shuffle','every-epoch', ...
'ValidationData',imdsTest, ...
'ValidationFrequency',floor(numel(imdsTrain.Files)/miniBatchSize), ...
'LearnRateSchedule','piecewise', ...
'LearnRateDropFactor',0.1, ...
'LearnRateDropPeriod',45);
net = trainNetwork(augmentedImdsTrain,layers,options);
the training starts, the display of the training starts with the indication: "initializing input data normalization"
However it stops quickly with the error message:
Error in test_parallel_cloud (line 77)
net = trainNetwork(augmentedImdsTrain,layers,options);
Caused by:
Error using nnet.internal.cnn.DistributedDispatcher/computeInParallel (line
193)
Error detected on worker 1.
Error using matlab.io.datastore.ImageDatastore/read (line 77)
Unable to read file: 's3://mybucket/cifar10/train/deer/image35398.png'.
Error using matlab.io.datastore/DsFileReader (line 113)
Could not find file : s3://mybucket/cifar10/train/deer/image35398.png
every time I rerun the code it seems to stop on another image it cannot read. However the image is always on the bucket and do not seems to be corrupt when I check using imshow.
Can you see where the problem is?
Fredhttps://nl.mathworks.com/matlabcentral/profile/authors/4730589-fredtag:nl.mathworks.com,2005:Question/5162782020-04-08T08:27:30Z2020-04-08T08:35:11ZMultiple 3d plots on one figurefigure(5)
for i=1:k+1
plot3(x(1,:),x(2,:),x(3,:),'-b',...
'linewidth',2,'markersize',9,'markerfacecolor','m');
hold on
plot3(xtopi(1,:),xtopi(2,:),xtopi(3,:),'-g',...
'linewidth',2,'markersize',9,'markerfacecolor','m');
plot3(xhat(1,:),xhat(2,:),xhat(3,:),'-r',...
'linewidth',2,'markersize',9,'markerfacecolor','m');
hold off
xlabel('koordinat X')
ylabel('koordinat Y')
zlabel('koordinat Z')
grid on
xlim([-inf inf])
ylim([-inf inf])
zlim([-inf inf])
end
toc
Hi, I have 3 pieces of data in a three-dimensional form, how do I display all these data in one figure? I want to plot all 3 on the 3d plot. How do I do that?
those data are [x(1),x(2),x(3)]; [xtopi(1),xtopi(2),xtopi(3)]; and [xhat(1),xhat(2),xhat(3)] on [x,y,z] plane
I have the following code.
Thank you for your answers.Muhammad Rifqi Hafizhhttps://nl.mathworks.com/matlabcentral/profile/authors/17684130-muhammad-rifqi-hafizhtag:nl.mathworks.com,2005:Question/3196432017-01-09T13:51:20Z2020-04-08T08:30:56ZDenoising of ECG SignalHello everyone How to remove baseline wandering noise of ECG Signal using wavelet transform in matlab? kindly help me or share a code with me.
Ammar Ahmad Afridihttps://nl.mathworks.com/matlabcentral/profile/authors/9313781-ammar-ahmad-afriditag:nl.mathworks.com,2005:Question/5162682020-04-08T07:37:31Z2020-04-08T08:29:09ZHow to Convert 3d matrix to row matrix???I have a 3d matrix in the workspace variable named WT.dec{1,1}, I need it to be converted to single dimention row matrix. How can do this???Mehul Jainhttps://nl.mathworks.com/matlabcentral/profile/authors/14926830-mehul-jaintag:nl.mathworks.com,2005:Question/4898312019-11-07T19:51:32Z2020-04-08T08:28:12Zyyaxis not working in app designer.Hi, I'm trying to plot a line on both the left and right side of a UIAxes in App Designer with the command yyaxis(myAxes, 'left'). I stripped down the problem to its most simple expression, a single figure with a UIAxes in it.
When I click on the graph I get that error:
Warning: Error occurred while executing the listener callback for event WindowMousePress defined for class
matlab.ui.Figure:
Unrecognized method, property, or field 'processFigureHitObject' for class 'matlab.ui.control.UIAxes'.
Error in matlab.graphics.internal.YYAxisEventManager
Error in matlab.graphics.internal.YYAxisEventManager
The code in the startupFcn is:
yyaxis(app.UIAxes, 'left');
x = pi:0.1:3*pi;
y = sin(x);
plot(app.UIAxes,x,y);
I use Matlab R2019b.
Anyone got an idea?David Levesquehttps://nl.mathworks.com/matlabcentral/profile/authors/8868401-david-levesquetag:nl.mathworks.com,2005:Question/5162752020-04-08T08:12:00Z2020-04-08T08:28:01ZWhy modifying the weights of a recurrent neural network does not cause the output to change when predicting on same data?I consider the following recurrent neural network (RNN):
where x is the input (a vector of reals), h the hidden state vector and y is the output vector. I trained the network "net" on MATLAB using some data x and obtained W, V, and U. I assumed that MATLAB uses equations of the form:
h(t) = tansig(net.LW{1,1} * h(t-1) + net.IW{1,1} * x(t)); y(t) = net.LW{2,1} * h(t)
However, this does not seem to be the case, since after changing matrix W to W', and keeping U,V the same, the output (y) of the RNN that uses W is the same as the output (y') of the RNN that uses W' when both predict on the same data x. Those two outputs should be different just by looking at the above equation (when I modify V or U, the outputs do change). How could I fix the code so that the outputs y and y' are different as they should be?
There is a relevant post here but it was inconclusive since the suggested equations did not match the matrices the OP was getting. That is why I decided to make a pretty similar question on this site after a few days of searching.
The relevant code is shown below:
[x,t] = simplefit_dataset; % x: input data ; t: targets
net = newelm(x,t,5); % Recurrent neural net with 1 hidden layer (5 nodes) and 1 output layer (1 node)
net.layers{1}.transferFcn = 'tansig'; % 'tansig': equivalent to tanh and also is the activation function used for hidden layer
net.biasConnect = [0;0]; % biases set to zero for easier experimenting
net.derivFcn ='defaultderiv'; % defaultderiv: tells Matlab to pick whatever derivative scheme works best for this net
view(net) % displays the network topology
net = train(net,x,t); % trains the network
W = net.LW{1,1}; U = net.IW{1,1}; V = net.LW{2,1}; % network matrices
Y = net(x); % Y: output when predicting on data x using W
net.LW{1,1} = rand(5,5); % This is the modified matrix W, W'
Y_prime = net(x) % Y_prime: output when predicting on data x using W'
max(abs(Y-Y_prime )); % The difference between the two outputs is 0 when it probably shouldn't be.
There is a chance that MATLAB's "newelm" does not take W into account after training is complete for some reason, but this does not seem to be the case since if the data {x,t} are fed into the net as cells instead, then the matrix W seems to have an effect on the output but not sure why:
[x,t] = simplefit_dataset; % x: input data ; t: targets
x = num2cell(x); t = num2cell(t); % convert x and t to type cell
net = newelm(x,t,5); % Recurrent neural net with 1 hidden layer (5 nodes) and 1 output layer (1 node)
net.layers{1}.transferFcn = 'tansig'; % 'tansig': equivalent to tanh and also is the activation function used for hidden layer
net.biasConnect = [0;0]; % biases set to zero for easier experimenting
net.derivFcn ='defaultderiv'; % defaultderiv: tells Matlab to pick whatever derivative scheme works best for this net
view(net) % displays the network topology
net = train(net,x,t); % trains the network
W = net.LW{1,1}; U = net.IW{1,1}; V = net.LW{2,1}; % network matrices
Y = net(x); % Y: output when predicting on data x using W
net.LW{1,1} = rand(5,5); % This is the modified matrix W, W'
Y_prime = net(x) % Y_prime: output when predicting on data x using W'
max(abs(cell2mat(Y)-cell2mat(Y_prime))) % The difference between the two outputs is not 0 in this case as it should be.
Edit: minor corrections.theo mamahttps://nl.mathworks.com/matlabcentral/profile/authors/14055907-theo-mamatag:nl.mathworks.com,2005:Question/5162702020-04-08T07:41:52Z2020-04-08T08:23:29ZBinary to decimal converter So, I wrote a program to convert a Binary value to decimal value without using str2num. Here's the code:
dec_val = 0;
base = 1;
bin_val = input('Enter a binary number:');
while bin_val >= 1
rem = mod(bin_val,10);
dec_val = dec_val + (rem * base);
bin_val = round(bin_val / 10);
base = base * 2;
end
fprintf('decimal value:%d\n',dec_val);
The problem is that when I enter digits greater than 16, the program does not respond. What changes should i make to enter more digits without using bin2dec or str2num?mrnice guyhttps://nl.mathworks.com/matlabcentral/profile/authors/15736874-mrnice-guytag:nl.mathworks.com,2005:Question/5153992020-04-04T21:26:35Z2020-04-08T08:23:28ZSpeeding up (vectorizing) barycentric interpolationDear All, I have the following problem:
is it possible to speed up the barycentric interpolation given below? I presume that vectorization could be particularly effective but I do not know how to do it. As the code has to be run many times (and the size of matrices involved is rather large) any increase in efficiency would be helpful. Could GPU computing, after vectorization, be of any help here?
na = 100;
nh = 100;
nm = 100;
nap = na+2;
nhp = nh+2;
H = randn(nap,nhp) ;
M = randn(nap,nhp) ;
MP = randn(nap,nhp) ;
ap_trial = NaN(nh,nm) ;
hp_trial = NaN(nh,nm) ;
mp_trial = NaN(nh,nm) ;
[h_grid,m_grid] = ndgrid(1:nh,1:nm);
[ap_grid,hp_grid] = ndgrid(1:nap,1:nhp);
tic
for r0 = 0:1
for r1 = 0:(nap-2)
for r2 = 0:(nhp-2) % loops picking up triangles constructed by adjacent points in matrices H and M
h1 = H(1+r1+r0,1+r2+r0);
h2 = H(1+r1,2+r2);
h3 = H(2+r1,1+r2);
m1 = M(1+r1+r0,1+r2+r0);
m2 = M(1+r1,2+r2);
m3 = M(2+r1,1+r2);
% barycentric interpolation (weights)
w1 = ( (m2-m3)*( h_grid -h3) + (h3-h2)*( m_grid -m3) ) / ( (m2-m3)*(h1-h3) + (h3-h2)*(m1-m3) );
w2 = ( (m3-m1)*( h_grid -h3) + (h1-h3)*( m_grid -m3) ) / ( (m2-m3)*(h1-h3) + (h3-h2)*(m1-m3) );
w3 = 1 - w1 - w2;
% preventing extrapolation
w1(w1 < 0) = NaN;
w2(w2 < 0) = NaN;
w3(w3 < 0) = NaN;
% barycentric interpolation (results)
ap = w1 * ap_grid(1+r1+r0,1+r2+r0) + w2 * ap_grid(1+r1,2+r2) + w3 * ap_grid(2+r1,1+r2);
hp = w1 * hp_grid(1+r1+r0,1+r2+r0) + w2 * hp_grid(1+r1,2+r2) + w3 * hp_grid(2+r1,1+r2);
mp = w1 * MP(1+r1+r0,1+r2+r0) + w2 * MP(1+r1,2+r2) + w3 * MP(2+r1,1+r2);
ap_trial( isnan(ap) == 0 ) = ap( isnan(ap) == 0 );
hp_trial( isnan(hp) == 0 ) = hp( isnan(hp) == 0 );
mp_trial( isnan(mp) == 0 ) = mp( isnan(mp) == 0 );
end
end
end
tocAdam Pigonhttps://nl.mathworks.com/matlabcentral/profile/authors/8440238-adam-pigon