Implementation of simulink model using a .m script
1 comentario
Respuesta aceptada
Más respuestas (1)
0 votos
Hi @Divyashree ,
After going through your comments, in order to read data from an Excel file within your Simulink model, you can utilize the From Spreadsheet block.
This block allows you to specify an Excel file from which it will read data. Here is how to configure it: Drag the From Spreadsheet block into your model. Set the File Name parameter to the path of your Excel file (e.g., myData.xlsx). Specify the Sheet Name if necessary. Ensure that your data is structured correctly: the first column should contain time data, and subsequent columns should contain signal values. If you have existing MATLAB scripts (like split_MM.m) as you mentioned in your comments, you can create a MATLAB Function block that calls these scripts: Create a new MATLAB Function block in your Simulink model. Open the MATLAB Function Block Editor by double-clicking the block. Define your function to call split_MM.m. For example:
function output = processData(input)
output = split_MM(input);
endIn this case, ensure that split_MM.m is accessible in your MATLAB path. After processing the data, if you want to write results back to an Excel sheet, use the To Workspace block
or another MATLAB script that utilizes the writetable or xlswrite functions: Create a new MATLAB script that takes your processed output and writes it back to an Excel file:
function writeOutputToExcel(data)
writetable(data, 'outputData.xlsx');
endIn your Simulink model: Connect the output of your From Spreadsheet block to the input of your MATLAB Function block. Connect the output of your MATLAB Function block to a To Workspace or another appropriate block for writing back to an Excel file. When you run the simulation:The From Spreadsheet block will read input data from your specified Excel file. Your custom processing logic in split_MM.m will execute via the MATLAB Function block. Finally, processed results can be written back to another Excel file. Ensure all paths are correctly set so that both reading from and writing to Excel files works seamlessly. The structure of your Excel files is crucial; verify that they conform to expectations (e.g., time-stamped format).
By following these steps, you should be able to effectively integrate your existing .m scripts with Simulink while leveraging Excel as both input and output sources for data processing.
Hope this helps.
11 comentarios
Hi @Divyashree,
After going through your comments and analysis of your errors you encountering, you need to understand that a nonscalar struct in MATLAB is an array of structures where each element can have different values. When you try to access fields like inputData.Serial_Number, if inputData is an array of structs, MATLAB needs to know which specific element you are referring to. Instead of directly accessing the field, you need to specify the index of the struct you want to access. For example, if you want to access the first element, use:
inputData(1).Serial_Number
If you need to process all elements, consider using a loop or array operations. Suppose your original code looks like this:
serialNumber = inputData.Serial_Number;
Change it to:
for i = 1:length(inputData)
serialNumber(i) = inputData(i).Serial_Number;
endEnsure that any operation you perform on structs is compatible with code generation. This means avoiding dynamic field names and ensuring that all array accesses are done with constant indices whenever possible. Use MATLAB’s debugging tools to step through your code and check the values and types of your variables at runtime.
https://www.mathworks.com/help/simulink/test-and-debug-simulations.html#
This will help identify where exactly the issue lies.
Hope this helps.
Hi @Divyashree,
The error indicates that there is a mismatch between the expected input dimensions of the MATLAB function block and the actual dimensions of the data being passed to it. The function is defined to process data with a fixed size of [1000, 30], but the output from the function is not conforming to this expected size. Upon reviewing the function, it is evident that the output processed_data is constructed from several columns extracted from the input data. The number of columns being combined into processed_data is 10, which means the output matrix will have a size of [N, 10], where N is the number of rows in the input data. This discrepancy in the number of columns is likely the root cause of the dimension mismatch. To resolve this issue, you need to ensure that the output of the MATLAB function matches the expected dimensions. Here are the steps to correct the problem:
Adjust the Output Size: Modify the size of the output variable processed_data to ensure it has the correct number of columns. If you need 30 columns in the output, you must either add more data to the output or adjust the input size accordingly.
Update the MATLAB Function: If the intention is to keep the output as [N, 10], then you should change the input size in the Simulink block to match this output. Here’s how you can modify the function:
function processed_data = filter_data(data) % Define column indices based on their actual positions in the file idx_Serial_Number = 1; idx_Part_Number = 3; idx_Tail_Number = 18; idx_MMs_Posted = 23; idx_Position = 4; idx_Removal_Reason = 5; idx_Preliminary_RC = 7; idx_RC_Description = 9; idx_Removal_Date = 15; idx_Program = 19;
% Extract columns based on indices
Serial_Number = data(:, idx_Serial_Number);
Part_Number = data(:, idx_Part_Number);
Tail_Number = data(:, idx_Tail_Number);
MM = data(:, idx_MMs_Posted);
LRU_Position = data(:, idx_Position);
Removal_Reason = data(:, idx_Removal_Reason);
Preliminary_RC = data(:, idx_Preliminary_RC);
RC_Description = data(:, idx_RC_Description);
Removal_Date = data(:, idx_Removal_Date);
Airplane_Model = data(:, idx_Program); % Combine into a single matrix
processed_data = [Serial_Number, Part_Number, Tail_Number, MM,
LRU_Position, ...Removal_Reason, Preliminary_RC,
RC_Description,Removal_Date, Airplane_Model]; % Ensure the output size is consistent
processed_data = reshape(processed_data, [], 10); % Adjust if
necessary
endUpdate Simulink Block: If you decide to keep the output as [N, 10], ensure that the input port in the MATLAB function block is set to accept a variable number of rows but fixed at 10 columns.
Hope this helps.
Hi @Divyashree ,
Please see my response to your comments below.
Size computation for 'processed_data' failed. Unknown var 'N' used in size definition.Size computation for 'processed_data' failed. Unknown var 'N' used in size definition. In the from spreadsheet model there is no changes, the file name, sheet name, range and the output datatype is same as I've mentioned before and connected all the 38 signals of the spreadsheet to a bus creator. Also in the workspace model there are no changes. I made few modifications in the simulink model. I've implemented a .m script for the bus creator and the block parameter I've mentioned it as outputdatatype: Bus:MyBusType, mode: bus object, MyBusType. The .m script I've mentioned below. The reason I've created this object code is
defineBusObject.m % Create the bus object busElements(38) = Simulink.BusElement; % Preallocation for 38 elements
% Define each element in the bus for i = 1:38 busElements(i).Name = ['Signal' num2str(i)]; busElements(i).Dimensions = 1; busElements(i).DataType = 'double'; end
% Assign to MyBusType MyBusType = Simulink.Bus; MyBusType.Elements = busElements;
% Save MyBusType in the base workspace
assignin('base', 'MyBusType', MyBusType);
After running the above object code, MyBusType will be in the base workspace.Before running the model, I executed the above script and made few modifications in the simulink model properties, that is Callback -> either in pre-loadfcn/InitFcn -> defineBusObject. After making this changes, I executed the model and I'm facing the above error.
Comments: Ensure that the variable N is defined in the MATLAB base workspace before running the Simulink model. You can do this by executing the following command in the MATLAB Command Window:
N = 38; % or whatever value is appropriate for your model
Your script for creating the bus object appears to be correct. However, ensure that the bus object is indeed being created and assigned to the base workspace before the model runs. You can verify this by checking the base workspace:
evalin('base', 'whos')
% This will list all variables in the base workspace
You mentioned using the InitFcn or PreLoadFcn callbacks to run the defineBusObject.m script. Ensure that these callbacks are correctly set up in the model properties. You can check this by right-clicking on the model background, selecting "Model Properties," and navigating to the "Callbacks" tab. Ensure that the script is correctly referenced:
defineBusObject
I've attached the snapshot of the model and the port and data manager. Also let me know should I need to make any changes in the ports and data manager of the matlab function. And also, Why am I geeting 1,1,1,1,1,1.... between the spreadsheet and buscreator model and '?' between bus creator and matlab function and workspace model.
Comments: If you are seeing unexpected values (like 1,1,1,1,1,1...) between the spreadsheet and the bus creator, it may indicate that the data is being interpreted incorrectly. Ensure that the data types in the Ports and Data Manager are consistent with what you expect. You can access the Ports and Data Manager by right-clicking on the bus creator block and selecting "Block Parameters." Check the data types and dimensions of the signals connected to the bus creator. To further debug the model, consider using the Simulink Debugger. You can set breakpoints in your model to inspect the values of variables at different points in the execution. This can help you identify where the unexpected values are being introduced. For reference, please click the link below.
https://www.mathworks.com/help/simulink/simulation-stepper.html
Regarding your issue with handling ‘?’ Between blocks, the ? symbol typically indicates a mismatch in data types or dimensions between connected blocks. Ensure that the output data type of the bus creator matches the expected input data type of the subsequent MATLAB function block. You can do this by checking the block parameters and ensuring that the data types are compatible. Can you please let me know, which data type is better to use? Double or string? Because it contains both alpha numeric characters. I've attached the snaps below.
Comments: Regarding your question about data types, if your data contains both alphanumeric characters, it is advisable to use a string data type. In MATLAB, you can use the string or char data types depending on your requirements. For example:
myData = "Sample123"; % Using string data type
Hope this helps.
Categorías
Más información sobre Event Functions en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!