How can I find the index of a specific element in a 1D array using Simulink?
Mostra commenti meno recenti
I`m working with Matlab Function Block in Simulink. Initially, this block is reading one variable (X) as input. The variable X changes over the time, so I`m capturing six samples and storing such samples in persistent variables. I`m also writing these samples in array format [1x6], that is:
persistent x0 x1 x2 x3 x4 x5
X_save = [x0 x1 x2 x3 x4 x5];
The objective is to compare another variable (y) and determine which elements of X is nearest to it. Suppose X = [0 10 20 30 40 50] while y = 7. I need Matlab Function to return as result the information w0 = 10 and w1 = 0, because x1 is closer to y than x0 is. I can easily implement this in workspace writing the functions below:
d = sort(abs(y - U(1,:)),'ascend'); % sort abs(y-U) in ascending order
Idx_1st = find(abs(y - U( ,:)) == d(1,1) ); % find index of x1 = 10
Idx_2nd = find(abs(y - U(1,:)) == d(1,2) ); % find index of x2 = 0
w0 = U(1,Idx_1st);
w1 = U(1,Idx_2nd);
W = [w0 w1];
That is, first I calculate the difference between y and all elements of X_save. Then, I sort the difference values (between y and X_save) in ascending order, so I can read the first the second element as the two nearest values. However, this workspace method doesn't work when implemented in Matlab Function Block (Simulink). It seems that the find(x) function can't be used properly. The diagnostic viewer is returning the following messages:
(1) 'W' is inferred as a variable-size matrix, but its size is specified as inherited or fixed. Verify 'y' is defined in terms of non-tunable parameters, or select the 'Variable Size' check box and specify the upper bounds in the Size box.
(2) Simulink cannot determine sizes and/or types of the outputs for block 'untitled/MATLAB Function' due to errors in the block body, or limitations of the underlying analysis. The errors might be inaccurate. Fix the indicated errors, or explicitly specify sizes and/or types for all block outputs.
Does anyone know why I`m having these issues? I appreciate any help. Thank you!
1 Commento
Eric Bernard Dilger
il 13 Apr 2022
Risposta accettata
Più risposte (0)
Categorie
Scopri di più su Simulink Functions in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!