Signal created with matlab function block in simulink - arrays

I want to generate an arbitrary linear signal from matlab function block in simulink. I have to use this block because then, I want to control when i generate the signal by a sequence in Stateflow. I try to put the out of function as a structure with a value field and another time as the following code:
`function y = sig (u)
if u == 1
t = ([0 10 20 30 40 50 60]);
T = [(20 20 40 40 60 60 0]);
S.time = [t '];
S.signals (1) values ​​= [T '].;
S.signals (1) = 1 dimensions.;
else
N = ([0 0 0 0 0 0 0]);
S.signals (1) values ​​= [N '].;
end
y = S.signals (1). values
end `
the idea is that u == 1 generates the signal, u == 0 generates a zero output.
I also try to put the output as an array of two columns (one time and another function value) with the following code:
function y = sig (u)
if u == 1
S = ([0, 0]);
cant = input ('Number of points');
for n = Drange (1: cant)
S (n, 1) = input ('time');
S (n, 2) = input ('temperature');  
end
y = [S]
else
y = [0]
end
end
In both cases I can not generate the signal.
In the first case I get errors like:
This structure does not have a field 'signals'; new fields can not be added When structure has-been read or used
or
Error in port widths or dimensions. Output port 1 of 'tempstrcutsf2/MATLAB Function / u' is a one dimensional vector with 1 elements.
or
Undefined function or variable 'y'. The first assignment to a local variable Determines its class.
And in the second case:
Try and catch are not supported for code generation,
Errors occurred During parsing of MATLAB function 'MATLAB Function' (# 23)
Error in port widths or dimensions. Output port 1 of 'tempstrcutsf2/MATLAB Function / u' is a one dimensional vector with 1 elements.
I'll be very grateful for any contribution.
PD: sorry for my English xD

You have many mistakes in your code
you have to read more about arrays and structs in matlab
here S = ([0, 0]); you're declare an array with only two elements so the size will be static
There is no function called Drange in mtlab except if it's yours
See this example with strcuts and how they are created for you function
function y = sig(u)
if u == 1
%%getting fields size
cant = input ('Number of points\r\n');
%%create a structure of two fields
S = struct('time',zeros(1,cant),'temperature',zeros(1,cant));
for n =1:cant
S.time(n) = input (strcat([strcat(['time' num2str(n)]) '= ']));
S.temperature(n) = input (strcat([strcat(['temperature'...
num2str(n)]) '= ']));
end
%%assign output as cell of struct
y = {S} ;
else
y = 0 ;
end
end
to get result form y just use
s = y{1};
s.time;
s.temperature;
to convert result into 2d array
2dArray = [y{1}.time;y{1}.temperature];
Work with arrays
function y = sig(u)
if u == 1
cant = input ('Number of points\r\n');
S = [];
for n =1:cant
S(1,n) = input (strcat([strcat(['time' num2str(n)]) '= ']));
S(2,n) = input (strcat([strcat(['temperature'...
num2str(n)]) '= ']));
end
y = S;
else
y = 0 ;
end
end

Related

Interactive plot to change array values (MATLAB)

N = 500;
pattern = zeros(N,N);
grid on
plot(pattern)
% gets coordinates of modified cells
[x,y] = ginput;
% convert coordinates to integers
X = uint8(x);
Y = uint8(y);
% convert (X,Y) into linear indices
indx = sub2ind([N,N],x,y);
% switch desired cells on (value of 1)
pattern(indx) = 1;
I'm trying to assign several elements of a zeros array the value of 1. Basically I want to create an interactive plot where the user decides what cells he wants to turn on and then save his drawing as a matrix. In Python it's very simple to use the on_click with Matplotlib, but Matlab is weird and I can't find a clear answer. What's annoying is you can't see where you clicked until you save your changes and check the final matrix. You also can't erase a point if you made a mistake.
Moreover I get the following error : Error using sub2ind Out of range subscript. Error in createPattern (line 12) indx = sub2ind([N,N],X,Y);
Any idea how to fix it?
function CreatePattern
hFigure = figure;
hAxes = axes;
axis equal;
axis off;
hold on;
N = 3; % for line width
M = 20; % board size
squareEdgeSize = 5;
% create the board of patch objects
hPatchObjects = zeros(M,M);
for j = M:-1:1
for k = 1:M
hPatchObjects(M - j+ 1, k) = rectangle('Position', [k*squareEdgeSize,j*squareEdgeSize,squareEdgeSize,squareEdgeSize], 'FaceColor', [0 0 0],...
'EdgeColor', 'w', 'LineWidth', N, 'HitTest', 'on', 'ButtonDownFcn', {#OnPatchPressedCallback, M - j+ 1, k});
end
end
Board = zeros(M,M);
playerColours = [1 1 1; 0 0 0];
xlim([squareEdgeSize M*squareEdgeSize]);
ylim([squareEdgeSize M*squareEdgeSize]);
function OnPatchPressedCallback(hObject, eventdata, rowIndex, colIndex)
% change FaceColor to player colour
value = Board(rowIndex,colIndex);
if value == 1
set(hObject, 'FaceColor', playerColours(2, :));
Board(rowIndex,colIndex) = 0; % update board
else
set(hObject, 'FaceColor', playerColours(1, :));
Board(rowIndex,colIndex) = 1; % update board
end
end
end
I found this link and modified the code to be able to expand the board and also select cells that have been turned on already to switch them off.
Now I need a way to extract that board value to save the array.

How can I find the nonzero values in a MATLAB cells array?

The following code generates an cell array Index [1x29], where each cell is an array [29x6]:
for i = 1 : size(P1_cell,1)
for j = 1 : size(P1_cell,2)
[Lia,Lib] = ismember(P1_cell{i,j},PATTERNS_FOR_ERANOS_cell{1},'rows');
Index1(i,j) = Lib % 29x6
end
Index{i} = Index1; % 1x29
end
How can I find the nonzero values in Index array?, i.e. generate an array with the number of non-zero values in each row of the Index1 array. I tried the following loop, but it doesn't work, it creates conflict with the previous one:
for i = 1 : length(Index)
for j = 1 : length(Index)
Non_ceros = length(find(Index{:,i}(j,:))); %% I just need the length of the find function output
end
end
I need help, Thanks in advance.
The nnz() (number of non-zeros) function can be used to evaluate the number of non-zero elements. To obtain the specific positive values you can index the array by using the indices returned by the find() function. I used some random test data but it should work for 29 by 6 sized arrays as well.
%Random test data%
Index{1} = [5 2 3 0 zeros(1,25)];
Index{2} = [9 2 3 1 zeros(1,25)];
Index{3} = [5 5 5 5 zeros(1,25)];
%Initializing and array to count the number of zeroes%
Non_Zero_Counts = zeros(length(Index),1);
for Row_Index = 1: length(Index)
%Evaluating the number of positive values%
Array = Index{Row_Index};
Non_Zero_Counts(Row_Index) = nnz(Array);
%Retrieving the positive values%
Positive_Indices = find(Array);
PositiveElements{Row_Index} = Array(Positive_Indices);
disp(Non_Zero_Counts(Row_Index) + " Non-Zero Elements ");
disp(PositiveElements{Row_Index});
end
Ran using MATLAB R2019b
for i = 1 : length(Index)
for j = 1 : length(Index)
Non_ceros(i,j) = nnz(Index{:,i}(j,:));
end
end

Array not defined

I'm still confused why am not able to know the results of this small algorithm of my array. the array has almost 1000 number 1-D. am trying to find the peak and the index of each peak. I did found the peaks, but I can't find the index of them. Could you please help me out. I want to plot all my values regardless the indexes.
%clear all
%close all
%clc
%// not generally appreciated
%-----------------------------------
%message1.txt.
%-----------------------------------
% t=linspace(0,tmax,length(x)); %get all numbers
% t1_n=0:0.05:tmax;
x=load('ww.txt');
tmax= length(x) ;
tt= 0:tmax -1;
x4 = x(1:5:end);
t1_n = 1:5:tt;
x1_n_ref=0;
k=0;
for i=1:length(x4)
if x4(i)>170
if x1_n_ref-x4(i)<0
x1_n_ref=x4(i);
alpha=1;
elseif alpha==1 && x1_n_ref-x4(i)>0
k=k+1;
peak(k)=x1_n_ref; // This is my peak value. but I also want to know the index of it. which will represent the time.
%peak_time(k) = t1_n(i); // this is my issue.
alpha=2;
end
else
x1_n_ref=0;
end
end
%----------------------
figure(1)
% plot(t,x,'k','linewidth',2)
hold on
% subplot(2,1,1)
grid
plot( x4,'b'); % ,tt,x,'k'
legend('down-sampling by 5');
Here is you error:
tmax= length(x) ;
tt= 0:tmax -1;
x4 = x(1:5:end);
t1_n = 1:5:tt; % <---
tt is an array containing numbers 0 through tmax-1. Defining t1_n as t1_n = 1:5:tt will not create an array, but an empty matrix. Why? Expression t1_n = 1:5:tt will use only the first value of array tt, hence reduce to t1_n = 1:5:tt = 1:5:0 = <empty matrix>. Naturally, when you later on try to access t1_n as if it were an array (peak_time(k) = t1_n(i)), you'll get an error.
You probably want to exchange t1_n = 1:5:tt with
t1_n = 1:5:tmax;
You need to index the tt array correctly.
you can use
t1_n = tt(1:5:end); % note that this will give a zero based index, rather than a 1 based index, due to t1_n starting at 0. you can use t1_n = 1:tmax if you want 1 based (matlab style)
you can also cut down the code a little, there are some variables that dont seem to be used, or may not be necessary -- including the t1_n variable:
x=load('ww.txt');
tmax= length(x);
x4 = x(1:5:end);
xmin = 170
% now change the code
maxnopeaks = round(tmax/2);
peaks(maxnopeaks)=0; % preallocate the peaks for speed
index(maxnopeaks)=0; % preallocate index for speed
i = 0;
for n = 2 : tmax-1
if x(n) > xmin
if x(n) >= x(n-1) & x(n) >= x(n+1)
i = i+1;
peaks(i) = t(n);
index(i) = n;
end
end
end
% now trim the excess values (if any)
peaks = peaks(1:i);
index = index(1:i);

Count items in one cell array in another cell array matlab

I have 2 cell arrays which are "celldata" and "data" . Both of them store strings inside. Now I would like to check each element in "celldata" whether in "data" or not? For example, celldata = {'AB'; 'BE'; 'BC'} and data={'ABCD' 'BCDE' 'ACBE' 'ADEBC '}. I would like the expected output will be s=3 and v= 1 for AB, s=2 and v=2 for BE, s=2 and v=2 for BC, because I just need to count the sequence of the string in 'celldata'
The code I wrote is shown below. Any help would be certainly appreciated.
My code:
s=0; support counter
v=0; violate counter
SV=[]; % array to store the support
VV=[]; % array to store the violate
pairs = ['AB'; 'BE'; 'BC']
%celldata = cellstr(pairs)
celldata = {'AB'; 'BE'; 'BC'}
data={'ABCD' 'BCDE' 'ACBE' 'ADEBC '} % 3 AB, 2 BE, 2 BC
for jj=1:length(data)
for kk=1:length(celldata)
res = regexp( data(jj),celldata(kk) )
m = cell2mat(res);
e=isempty(m) % check res array is empty or not
if e == 0
s = s + 1;
SV(jj)=s;
v=v;
else
s=s;
v= v+1;
VV(jj)=v;
end
end
end
If I am understanding your variables correctly, s is the number of cells which the substring AB, AE and, BC does not appear and v is the number of times it does. If this is accurate then
v = cellfun(#(x) length(cell2mat(strfind(data, x))), celldata);
s = numel(data) - v;
gives
v = [1;1;3];
s = [3;3;1];

Attempt to index field ? (a nil value)

I am writing a small RPG game engine with Lua/love2d, and I need to parse a file to a 2d array, but it don't work, and I am getting errors...
main.lua :
local fmap = love.filesystem.read("map.txt")
map = {}
for c in fmap:gmatch(".") do
if c == "\n" then
y = 0
x = x + 1
else
map[x][y] = c -- this won't work
y = y + 1
end
end
map.txt :
6777633333
6558633333
6555614133
7757711112
2111111112
2111111112
2222222222
You can't use multi-dimensional array like this. See Matrices and Multi-Dimensional Arrays
You can transform your code like this :
local fmap = love.filesystem.read("map.txt")
map = {}
x = 0
y = 0
map[x] = {}
for c in fmap:gmatch(".") do
if c == "\n" then
y = 0
x = x + 1
map[x] = {}
else
map[x][y] = c -- this won't work
y = y + 1
end
end
I know that this has already been answered, but you'd probably find my (in progress) tile tutorial useful. The strings section deals with exactly the issue you are having.

Resources