Not enough input arguments when using For Loop over an Integral - matlab

When I run the following code in matlab, I get the "Not enough input arguments."
It is not clear to me what I am doing wrong. I have checked it over an over again, but obviously what I intend and what the computer says I intend do not match up.
tau = 50e-3;
b= 1;
dt = .2;
time=1:dt:100;
w = 1; W= w;
inte = zeros(1, length(time));
inte(1) = 0;
Ds = #(s) (w*s-s+b)*(1/tau);
for i=1:length(time)
inte(i) = integral(Ds,0,time(i));
end
My hope was that the loop would integrate with different values of time from the time array. Instead, it appears to be looping through and only integrating once.
Any and all help is appreciated.
Update to include full error message:
% Validate the first three inputs.
narginchk(3,inf);
if ~isa(fun,'function_handle')
error(message('MATLAB:integral:funArgNotHandle'));
end
if ~(isscalar(a) && isfloat(a) && isscalar(b) && isfloat(b))
error(message('MATLAB:integral:invalidEndpoint'));
end
opstruct = integralParseArgs(varargin{:});
Q = integralCalc(fun,a,b,opstruct);

Related

How to adjust the size of block.outputport.data in Matlab?

I have tried to generate a square pulsed clock. But it gives error. I tried this:
function pll( block)
setup(block);
function setup(block)
% Register number of ports
block.NumInputPorts = 1;
block.NumOutputPorts = 1;
% Override input port properties
block.InputPort(1).Dimensions = 1;
block.InputPort(1).DatatypeID = 8; % boolean
block.InputPort(1).Complexity = 'Real';
block.InputPort(1).DirectFeedthrough = false;
% Override output port properties
block.OutputPort(1).Dimensions = 1;
block.OutputPort(1).DatatypeID = 0; %double
block.OutputPort(1).Complexity = 'Real';
block.NumDialogPrms = 1;
block.DialogPrmsTunable = 0;
ts = 1/24000000'; %'
block.sample times= [ts 0];
block.SimStateCompliance = 'DefaultSimState'
function Outputs(block)
t = [0:1/(24000000):0.000001];
l = 0.1*exp(-6);
c = 220*exp(-9) + 60*exp(-9);
f = 1/(2*pi*sqrt(l*c));
block.OutputPort(1).Data = square(2*pi*f*t);
function Terminate(block)
But it gives me the error
"Error evaluating registered method 'Outputs' of M-S-Function 'pll' in
'untitled/Level-2 M-file S-Function'. Invalid assignment in
'untitled/Level-2 M-file S-Function': attempt to assign a vector of
width 24001 to a vector of width 1."
the error indicates on the line
block.OutputPort(1).Data = square(2*pi*f*t);
so what can be done to overcome this error?
It seems from your example that you're not really familiar with the way Simulink works. At each time step, each block in a Simulink model outputs a value (i.e the block's output value) corresponding to the current simulation time. In your case, within the block.Output function you are trying to output all time points at every simulation time step.
It appears that what you really want is to replace
t = [0:1/(24000000):0.000001];
with
t = block.CurrentTime;
And replace
block.OutputPort(1).Data = square(2*pi*f*t);
with
block.OutputPort(1).Data = sign(sin(2*pi*f*t));
Also, some other things to consider:
you don't seem to be registering the block's output method using:
block.RegBlockMethod('Outputs',#Output);
Why have you defined the block to have an input when it doesn't seem to require one?
Why are you doing this in an S-Function when a From Workspace block (or one of the many other ways to get data into a model) would seem to make more sense?

Matlab and "Error while evaluating UIcontrol callback"

I have a matlab file that I can't post here (3000 lines) which contains a lot of functions which are used from a GUI.
I am working with matlab file that contains the 3000 lines which has so many functions for design GUI
when I am using Function A that function which are related to uses the several other functions and make it as for loop that run many time function A (1600-2000) times of iterations through taking a long time.
when I reached at 400-500 Matlab gives me
error : "Error while evaluation UIcontrol callback"
I must to kill the existing process and then exit Matlab and run again from the previous iteration which give the error. So my problem is not based on the function call but it may comes based on memory or may be temporary memory.
Does it possible to increase the temporary memory uses by Matlab ?
I increase the preference "Java heat memory" at maximum but this preference change nothing to my problem.
Is there any way to solve this issue ?
A part of the script :
function CalculateManyOffset % It's Function A on this topic
mainfig = FigHandle;
parameters = get(mainfig,'UserData');
dbstop if error
NumberofProfiles = str2double(get(parameters.NumberofProfilesBox,'string'));
step = str2double(get(parameters.DistBetweenProfilesBox,'string'));
Alphabet=('A':'Z').';
[I,J] = meshgrid(1:26,1:26);
namered = [Alphabet(I(:)), Alphabet(J(:))];
namered = strvcat(namered)';
nameblue = [Alphabet(I(:)), Alphabet(J(:))];
nameblue = strvcat(nameblue)';
apostrophe = '''';
SaveNameDisplacementFile = [get(parameters.SaveNamebox,'string'),'.txt'];
a=0;
icounter = 0;
StartBlue = str2double(get(parameters.bluelinebox,'String'));
EndBlue = StartBlue + NumberofProfiles;
StartRed = str2double(get(parameters.redlinebox,'String'));
EndRed = StartRed + NumberofProfiles-15;
for i = StartBlue:step:EndBlue;
icounter = icounter +1;
jcounter = 0;
for j=StartRed:step:EndRed;
jcounter = jcounter +1;
opthorz = [];
maxGOF = [];
a=[a(1)+1 length(StartRed:step:EndRed)*length(StartBlue:step:EndBlue)]
%
if a(1) >= 0 && a(1) <= 20000
BlueLineDist = 1*i;
parameters.bluelinedist = i;
RedLineDist = 1*j;
parameters.redlinedist = j;
parameters.i = icounter;
parameters.j = jcounter;
set(mainfig,'UserData',parameters,'HandleVisibility','callback'); % To update variable parameters for the function which use them (downside : BlueLine, RedLine, GetBlueProfile, GetRedProfile, CalculateOffset)
BlueLine;
RedLine;
GetBlueProfile;
GetRedProfile;
CalculateOffset;
% Now, reload variable parameters with new value calculate on previous functions
mainfig = FigHandle;
parameters = get(mainfig,'UserData');
opthorz = parameters.opthorz;
name = [num2str(namered(:,jcounter)'),num2str(nameblue(:,icounter)'),apostrophe];
namefid2 = [num2str(namered(:,jcounter)'),' - ',num2str(nameblue(:,icounter)'),apostrophe];
Distance = [num2str(RedLineDist),' - ',num2str(BlueLineDist)];
maxGOF = parameters.maxGOF;
% Create file with all displacements
if a(1) == 1;
fid2 = fopen(SaveNameDisplacementFile,'w');
fprintf(fid2,['Profile red - blue\t','Distance (m) between profile red - blue with fault\t','Optimal Displacement\t','Goodness of Fit\t','20%% from Goodness of Fit\t','Minimal Displacement\t','Maximal Displacement \n']);
fprintf(fid2,[namefid2,'\t',Distance,'\t',num2str(opthorz),'\t',num2str(maxGOF),'\t',num2str(parameters.ErrorGOF),'\t',num2str(parameters.ErrorDisp(1,1)),'\t',num2str(parameters.ErrorDisp(1,2)),'\n']);
elseif a(1) ~= b(end);
fid2 = fopen(SaveNameDisplacementFile,'a');
fprintf(fid2,[namefid2,'\t',Distance,'\t',num2str(opthorz),'\t',num2str(maxGOF),'\t',num2str(parameters.ErrorGOF),'\t',num2str(parameters.ErrorDisp(1,1)),'\t',num2str(parameters.ErrorDisp(1,2)),'\n']);
else
fid2 = fopen(SaveNameDisplacementFile,'a');
fprintf(fid2,[namefid2,'\t',Distance,'\t',num2str(opthorz),'\t',num2str(maxGOF),'\t',num2str(parameters.ErrorGOF),'\t',num2str(parameters.ErrorDisp(1,1)),'\t',num2str(parameters.ErrorDisp(1,2))]);
fclose(fid2);
end
end
end
end

Program an iteration which will be stopped when the mentioned circumstance is met

Hi everyone I have encountered a problem in writing a programming code for the algorithm as shown below
This program is going to be terminated when the approximate error which is defined as (current approximation-previous approximation)/current approximation is less than 0.01. It can be simplified as (f(xr)i+1 - f(xr)i)/f(xr)i+1. Below are the code that I have written and I would really like to know how can I program an iteration which will be stopped when the mentioned circumstance is met.
xl = input('Enter lower limit : ');
xu = input('Enter upper limit : ');
xr = (xl+xu)/2;
R = 3; V = 30;
fl = (pi*R*xl^2)-(pi*(xl^3)/3)-V; % between is there anyway can call these functions
fu = (pi*R*xu^2)-(pi*(xu^3)/3)-V; other than typing 3 times
fh = (pi*R*xr^2)-(pi*(xr^3)/3)-V;
while relative error is less than 0.01 then display value of xr
if fl*fu<0
xu = xr;
elseif fl*fu>0
xl = xr;
end
end
I updated the code now that I could run it. I tested it with f(x)=x^2-2. It converges to 1.4141 in 6 iterations. I suggest you compare that code with what you had to understand what was not working for you before. This will be a good learning experience.
>> example(1,2);
Crossing found after 6 iterations: 1.414062
where example.m is the following:
function xr = root(xl,xu)
MAX_NUMBER_ITERATIONS = 1000;
MAX_DELTA=.01;
numberIterations=0;
xr_old=xu;
xr = (xl+xu)/2;
while ((numberIterations<MAX_NUMBER_ITERATIONS) & (abs(xr_old-xr)>=MAX_DELTA))
numberIterations=numberIterations+1;
xr_old = xr;;
product=f(xl)*f(xr);
if product<0
xu = xr;
xr = (xl+xu)/2;
continue;
elseif product>0
xl = xr;
xr = (xl+xu)/2;
continue;
else
break;
end
end
fprintf('Crossing found after %d iterations: %f\n',numberIterations,xr)
end
function y = f(x)
y=x^2-2;
end
You forgot to implement Step 3(c).
You also didn't "return to step 2" in steps 3(a) and 3(b) as the instructions state. To do that, you will need to create a while loop as described here; put in your while loop the condition that will keep it looping. If that condition evaluates to false, it should drop out of the loop in accordance with step 3(c).
Use CONTINUE to fulfill the "Return to Step 2" part in steps 3(a) and 3(b); that moves execution back to the top of the loop. See also Jump command in MATLAB
Good luck.
you can put calculation in a function:
function f = some_function(x)
R = 3;
V = 30;
f = (pi*R*x^2)-(pi*(x^3)/3)-V;
You can try with 100 passes (for safety):
for i=1:100
xr_old = xr
fr_old = fr
xr = (xl+xu)/2;
fr = some_function(xr);
if abs((xr - xr_old)/xr) < MIN_STEP
break
end
temp = fl*fr
if temp < 0:
xu = xr
fu = fr
else if temp > 0:
xl = xr
fl = fr
end
end

lagranges method

I found following code on internet. I am new to matlab. Now the problem whenever i copy-paste this code then it shows me error message.
function[p] = lagrange_interpolation(X,Y)
|
Error: Function definitions are not permitted in this context.
The code snippet is:
function[p] = lagrange_interpolation(X,Y)
L = zeros(n);
p = zeros(1,n);
% computing L matrice, so that each row i holds the polynom L_i
% Now we compute li(x) for i=0....n ,and we build the polynomial
for k=1:n
multiplier = 1;
outputConv = ones(1,1);
for index = 1:n
if(index ~= k && X(index) ~= X(k))
outputConv = conv(outputConv,[1,-X(index)]);
multiplier = multiplier * ((X(k) - X(index))^-1);
end
end
polynimialSize = length(outputConv);
for index = 1:polynimialSize
L(k,n - index + 1) = outputConv(polynimialSize - index + 1);
end
L(k,:) = multiplier .* L(k,:);
end
% continues
end
In all likelihood, you are probably attempting to mix random code along with your function. There are two types of M files:
scripts - have "random" code that is executed independent of anything else
functions - are the "classic" definition of functions
You cannot mix the two (that's a lie, but for now a good one). So if you are defining a function, that should be the only code in your .m file.
You should later use this function in either the command window or another function or a script by calling it via p = blahblah(bleaurgh);.
TL;DR: Make sure the function code is the only code in the script file, save it with the same name.m, call the function from somewhere else.

Parfor-loop not working, how to fix?

I am trying to parallize two of my for-loops and run it on a remote cluster.
I am using matlabpool open local 12 at the beginning with matlabpool close at the end. The problem I am running into is that my parfor-loop cannot use my matric properly and I am not sure how I would rewrite it so that it works.
H = hadamard(n);
H = [H;-H];
P = setdiff(P,H,'rows');
[r,c] = size(P);
A = zeros(n,r);
parfor i=1:r
for j=1:n
d = P(i,:) + H(j,:);
A(j,i) = sum(d(:) ~= 0);
end
end
and:
u2Had = cell(2,r);
parfor i =1:r
u2Had{1,i} = min(A(:,i));
MinHadIndex = find(A(:,i) == u2Had{1,i});
u2Had{2,i} = MinHadIndex;
end
Those are the two segments of the code I am trying to parallize. Any help is much appreciated and if I need to add anymore information please ask.
I don't know what your problem is in the first part as it works fine (perhaps if you defined P better)
regarding the second part, you can only send information to and from parloops in narrow cases.
Here change your code to the following:
u2HadT = cell(1,r);
parfor i =1:r
temp = min(A(:,i));
MinHadIndex = find(A(:,i) == temp);
u2HadT{i} = {temp;MinHadIndex};
end
u2Had = cell(2,r);
for i =1:r
u2Had{1,i} = u2HadT{i}(1);
u2Had{2,i} = u2HadT{i}(2);
end