How to adjust the size of block.outputport.data in Matlab? - 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?

Related

Call a function within a function matlab

I have defined a function called CARE_SAV which contains a recursive process, the code is
function [miu_tau_c,miu_tau] = CARE_SAV(beta,Yt,t,miu_1)
global miu_tau
global t
global miu_1
if t > 1
miu_tau_c = beta(1)+beta(2) * ...
[CARE_SAV(beta, Yt, t-1, miu_1)]+beta(3)*abs(Yt(t-1));
miu_tau = [miu_tau;miu_tau_c];
else
miu_tau_c = miu_1;
miu_tau = [miu_tau;miu_tau_c];
end
The function itself runs perfectly. However, when I define another function (ALS) and call this CARE_SAV, the error keeps popping out saying the local variable may have been changed to match local variable value. And hence there is error on ALS line 6. The ALS code is shown below
function sum = ALS(tau,Yt,beta,miu_1,CARE_SAV)
s = 0; % set the initial value for the ALS sum
global t
global miu_1
t = size(Yt,1); % indicate the length of the simulated data
[~,miu_tau]=CARE_SAV(beta,Yt,t,miu_1); % call the CARE_SAV function to get miu_tau value
for i = 1:size(Yt,1) % conduct the ALS summation process for each t
if Yt(i) < miu_tau(i) % set the indicator function
s = s+abs(tau-1)*(Yt(i) - miu_tau(i))^2;
else
s = s+abs(tau-0)*(Yt(i) - miu_tau(i))^2;
end
end
sum = s;
Can someone explain to me what I happening here? Much appreciated.
In CARE_SAV, you have this:
miu_tau_c = miu_1; - being miu_1 a global variable.
Then, in the other function, you have as input miu_1 AGAIN and you call global miu_1 AGAIN. This is the issue.
Try to remove miu_1 from input in the second function. It might work, but using globals in functions like this it's not recommended.

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

MatLab - Error using run => Input argument is undefined

As a MatLab newbie, I have problems running the following script:
function [ newarray ] = reshapeIm( array, period )
%reshapeIm(array, period) Summary of this function goes here
% Detailed explanation goes here
le = length(array);
fra = le/period;
array = [array, zeros(1, ceil(fra)*period-le)];
newarray = reshape(array', period, []);
end
load('1200rpm_shak3.mat');
cRounds = 54;
mylength = 100;
thetas = (1:cRounds*mylength).*2*pi/mylength;
thetas0 = (1:mylength).*2*pi/mylength;
figure;
plot(z1(1:300), '.-');
plot(z2(1:300), '.-');
z1s = z1;
z2s = [z2(mylength/4+1:end) z2(1:mylength/4)];
z3s = [z3(mylength/2+1:end) z3(1:mylength/2)];
z4s = [z4(mylength*3/4+1:end) z4(1:mylength*3/4)];
dr = 1/4.*(z1s+z2s+z3s+z4s); % gemittelt
drs = reshapeIm(dr, mylength);
drs_std = std(drs, 1, 2);
drs_meanstd = mean(drs_std);
figure;
polar(thetas, 250000+200*dr);
figure;
polar(thetas0', 250000+200*mean(drs,2));
The command window says:
??? Error using ==> run
Input argument 'array' is undefined.
I suppose, that's because the script was written for a newer MatLab, but I use 5.3.
Functions need to be in their own files. You cannot define functions within a script file. So, to get your code to work at all, you need to move the function that is at the top of your file (which I copied below) into its own file. Name the file "reshapeIM.m" and save it in the same directory where you are doing your work.
function [ newarray ] = reshapeIm( array, period )
%reshapeIm(array, period) Summary of this function goes here
% Detailed explanation goes here
le = length(array);
fra = le/period;
array = [array, zeros(1, ceil(fra)*period-le)];
newarray = reshape(array', period, []);
end
Then, after removing the function from your script, save your script and run it again. This should solve the problem with regards to the function. You may have other errors, but this should take care of the error that you reported.

MATLAB SHARC ADSP-21369 BTC failure

I am implementimg a BTC from matlab to the SHARC ADSP-21369 EZ-Kit to edit parameters for a simple 3-band-EQ during the board's runtime.
I have a class in MatLAB including the methods for accessing, writing and reading the BTC and i have initialized the channels in VisualDSP++ like shown in the getting started example.
My problem is as follows:
I transmit filter coefficients for a biquad filter, so the numerator-coefficients are 3x1 cell array, and the denominator-coeffs are a 2x1 cell array
If i try to send these values through the BTC, the BTC memory window shows me that only one single coefficient of the array is edited, the others get 0. A very interesting point is, that in the 3x1 cell array the 2nd coefficient is edited, the first and the third get zero.
I need to present this work on Monday, so quick solutions are appreciated.
The function code is below.
classdef accessBTC < handle
properties
numChannels = [];
isInitialized = 0; %Logical 0 or 1 to indicate if the class is instantiated to connect to the VisualDSP session
end
properties(SetAccess = private)
channelList = {}; % Array of channel objects
end
methods
function initialize(obj)
a = actxserver('VisualDSP.ADspApplication');
btcPlugin = a.PluginList.invoke('Item','BtcManager');
btcManager = btcPlugin.Open;
btcChannelList = btcManager.ChannelList(int16(0)); % Get the channel list in processor #0 (always INT16)
obj.numChannels = btcChannelList.Count;
disp(['Total Number of Channels: ', num2str(obj.numChannels)]);
% Create the BTC Channel interfaces
for i = 1: obj.numChannels
obj.channelList{i} = btcChannelList.invoke('Item',int32(i-1));
end
obj.isInitialized = 1;
% S=saveobj(obj);
end % End of Method: INITIALIZE
function outVal = read(obj,channelNum,width)
% Default width is 32; other possible values: 16, 8
% Channel num starts frm 0
if nargin ==2
width = 32;
end
widthStr = ['btcWidth',num2str(width)];
btcChan = obj.channelList{channelNum};
out_val = btcChan.Read(widthStr);
outVal = cell2mat(out_val);
end % End of Method: READ
function write(obj, channelNum, val)
% input val needs to be a scalar or a vector of int32 or in16 or
% int8 values
% Channel num starts frm 0
if nargin ~=3
error('WRITE method for accessBTC object needs 2 inputs.')
end
btcChan = obj.channelList{channelNum+1};
btcChan.Write('btcWidth32',num2cell(val));
end %End of Method: WRITE
function reset(obj)
obj.numChannels = [];
obj.isInitialized = 0;
obj.channelList = [];
end %End of Method: RESET
end
so if i sending for example these single arrays
num_1 = [1.324; -1.45; 0.83]
den_1 = [-1.45; 0.74]
i am getting in my BTC memory window as floating point
num_1 = [0.0000000; -1.45; 0.0000000]
den_1 = [-1.45; 0.0000000]
has anybody an idea how to fix this?
i will add some pictures now, that you can cisualize my problem:
matlab-debug
vdsp-debug
thanks a lot and best regards,
markus

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.