Implementation of simulink model using a .m script

I have a .m scripts. It takes the excel sheets as input, performs analysis and output is again excel sheets. Similarly to .m scripts, how to implement simulink model?
split_MM.m is called in Processed_NVM_Fault_History.m

 Respuesta aceptada

Aravind
Aravind el 29 de Oct. de 2024
It seems you're looking to process data from Excel sheets using Simulink and then save the results back into Excel.
To achieve this, you would need to first read the excel file in Simulink, process it record by record and then store the output into a modified excel file.
Reading an Excel File in Simulink:
To read data from an Excel file in Simulink, you can use the "From Spreadsheet" block. This block allows you to import data from Excel spreadsheets as a signal into your Simulink model. More details can be found at the following documentation link: https://www.mathworks.com/help/releases/R2019b/simulink/slref/fromspreadsheet.html.
Processing the Data in Simulink:
You can process the data read from the Excel file by creating a Simulink model that replicates the analysis performed in you “.M” script. This could involve using blocks for mathematical operations, logic, filtering, or any other processing required. You could use blocks like Math Operations, Signal Processing, and Logic and Bit Operations to build the analysis logic.
Additionally, you can also consider using the “MATLAB Function” blocks for complex calculations or custom scripts.
Storing the Modified Data to Another Excel File:
To save the processed data back into an Excel file, use the "To Workspace" block to write the signal data to a variable in the MATLAB workspace. Then, you can use the "writetable" function in MATLAB to export this data to an Excel file. More information about the "To Workspace" block can be found here: https://www.mathworks.com/help/releases/R2019b/simulink/slref/toworkspace.html.
Here are some additional resources to help you with this process:
  1. The “MATLAB Function” block: https://www.mathworks.com/help/releases/R2019b/simulink/ug/what-is-a-matlab-function-block.html
  2. Math Operations in Simulink: https://www.mathworks.com/help/releases/R2019b/simulink/math-operations.html
  3. Logic and Bit Operations in Simulink: https://www.mathworks.com/help/releases/R2019b/simulink/logic-and-bit-operations.html
  4. “writetable” function: https://www.mathworks.com/help/releases/R2019b/matlab/ref/writetable.html
  5. An example on using the “To Workspace” block: https://www.mathworks.com/help/releases/R2019b/simulink/slref/output-simulation-data-with-blocks.html
Hope this helps!

Más respuestas (1)

Umar
Umar el 29 de Oct. de 2024

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.

fromSpreadsheet

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);
     end

In 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

toworkspace

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');
     end

In 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

Divyashree
Divyashree el 29 de Oct. de 2024
Can you do the implementation of the simulink model?
Umar
Umar el 29 de Oct. de 2024
Hi @Divyashree,
If you click the links above in the comments provided above, you should be able to implement it. It is very simple and straightforward. However, I used to have access to Simulink months ago but couldn’t afford it anymore. Hope this helps.
Hi,
I implemented as mentioned above. But I'm unable to generate an excel file in the local and facing the below mentioned error:
Directly accessing field or property of nonscalar struct or object not supported for code generation. Function 'MATLAB Function2' (#84.633.656), line 13, column 27: "inputData.Serial_Number" Launch diagnostic report.
Component:MATLAB Function | Category:Coder error
Directly accessing field or property of nonscalar struct or object not supported for code generation. Function 'MATLAB Function2' (#84.686.707), line 14, column 25: "inputData.Part_Number" Launch diagnostic report.
Component:MATLAB Function | Category:Coder error
Directly accessing field or property of nonscalar struct or object not supported for code generation. Function 'MATLAB Function2' (#84.737.758), line 15, column 25: "inputData.Tail_Number" Launch diagnostic report.
Component:MATLAB Function | Category:Coder error
Directly accessing field or property of nonscalar struct or object not supported for code generation. Function 'MATLAB Function2' (#84.789.807), line 16, column 26: "inputData.Position" Launch diagnostic report.
Component:MATLAB Function | Category:Coder error
Directly accessing field or property of nonscalar struct or object not supported for code generation. Function 'MATLAB Function2' (#84.840.864), line 17, column 28: "inputData.Removal_Reason" Launch diagnostic report.
Component:MATLAB Function | Category:Coder error
Directly accessing field or property of nonscalar struct or object not supported for code generation. Function 'MATLAB Function2' (#84.897.921), line 18, column 28: "inputData.Preliminary_RC" Launch diagnostic report.
Component:MATLAB Function | Category:Coder error
Directly accessing field or property of nonscalar struct or object not supported for code generation. Function 'MATLAB Function2' (#84.954.978), line 19, column 28: "inputData.RC_Description" Launch diagnostic report.
Component:MATLAB Function | Category:Coder error
Directly accessing field or property of nonscalar struct or object not supported for code generation. Function 'MATLAB Function2' (#84.999.1011), line 20, column 16: "inputData.MM" Launch diagnostic report.
Component:MATLAB Function | Category:Coder error
Directly accessing field or property of nonscalar struct or object not supported for code generation. Function 'MATLAB Function2' (#84.1044.1068), line 21, column 28: "inputData.Airplane_Model" Launch diagnostic report.
Component:MATLAB Function | Category:Coder error
Directly accessing field or property of nonscalar struct or object not supported for code generation. Function 'MATLAB Function2' (#84.1099.1121), line 22, column 26: "inputData.Removal_Date" Launch diagnostic report.
Component:MATLAB Function | Category:Coder error
Errors occurred during parsing of MATLAB function 'sim_processed_SED_BITE/MATLAB Function2'
Component:MATLAB Function | Category:Coder error
Errors occurred during parsing of MATLAB function 'sim_processed_SED_BITE/MATLAB Function2'
Umar
Umar el 3 de Nov. de 2024

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;
     end

Ensure 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.

I tried another different approach. For the matlab function, in the ports and data manager I've mentioned size as [1000,30] and data type as double. For the from spreadsheet block, I've mentioed the output data type as 2-D array. For the to workspace block, I've given save format as array. But facing the below mentioned errors.
Simulink cannot unify the dimensions of the multiplexed signal at output port 1 of 'processed_SED/MATLAB Function' to match the input dimension of input port 1 of 'processed_SED/MATLAB Function'. Specifically, Simulink cannot unify {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1} to match [1000x30]. Consequently, Simulink cannot propagate dimension information from output port 1 of 'processed_SED/MATLAB Function' to input port 1 of 'processed_SED/MATLAB Function'.
Error in port widths or dimensions. Invalid dimension has been specified for input 'data'.
Error occurred in 'processed_SED/MATLAB Function'.
I've attached the file. Can you help me out in this?
Umar
Umar el 5 de Nov. de 2024
Hi @ Divyashree,
As I mentioned in my prior comments that I don’t have access to Simulink. So, do you want me to proceed by providing analysis of your comments, please let me know.
Hi @Umar,
Sure you can give me the analysis for the above error. Since you do not have access to the simulink, I'll explain how I've created the model. Using from spreadsheet block, I've loaded the excel sheet. For the block paramaters, I've mentioned the file name, sheet name, range - A1:AL31 and output data type as double. There is 38 output signals from the spreadsheet, which I've connected to the bus creator and the output of the bus creator I've connected to the matlab function block and written a function for processing the data in the excel. the matlab function is mentioned below:
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];
end
For the matlab function block, in ports and data manager for data input I've specified the size as fixed size - [1000,30] and type as double. Then the matlab function block is connected to the to workspace. I've given the variable name as processed_data and the save format I've mentioned as array (2-D array). If I run this complete model, I'm getting the error which I've mentioned above. I'll mention it again.
ERROR:
Simulink cannot unify the dimensions of the multiplexed signal at output port 1 of 'processed_SED/MATLAB Function' to match the input dimension of input port 1 of 'processed_SED/MATLAB Function'. Specifically, Simulink cannot unify {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1} to match [1000x30]. Consequently, Simulink cannot propagate dimension information from output port 1 of 'processed_SED/MATLAB Function' to input port 1 of 'processed_SED/MATLAB Function'.
Error in port widths or dimensions. Invalid dimension has been specified for input 'data'.
Error occurred in 'processed_SED/MATLAB Function'.
Umar
Umar el 5 de Nov. de 2024

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
  end

Update 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 @Umar, I updated the matlab function as per you suggestion.
I'm facing the another error,
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.
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.
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.
Umar
Umar el 7 de Nov. de 2024

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.

Iniciar sesión para comentar.

Categorías

Productos

Versión

R2019b

Preguntada:

el 29 de Oct. de 2024

Comentada:

el 7 de Nov. de 2024

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by