Assigning elements or an array within a Bus

10 次查看(过去 30 天)
Hi,
I have a Bus that is a structure of Buses where some of them are simple types with large dimensions.
E.G
"BusType1" = A bus structure with elements A,B and C of type Boolean,Boolean and Int32 respectively.
"Bus.Bus_Child_1" is of type "BusType1" with 30 Dimensions
Within my model I would like to assign some of the elelements of in Bus_Child_1.
I have currently been performing this using a matlab function within the model. Similar to this:
function Bus = fcn(DefaultBusValues,AInput,BInput,CInput)
Bus = DefaultBusValues;
for idx = 1:length(AInput)
Bus.Bus_Child_1(idx).A = Boolean(AInput(idx));
Bus.Bus_Child_1(idx).B = Boolean(AInput(idx));
Bus.Bus_Child_1(idx).C = Int32(AInput(idx));
end
Using this Implementation I'm finding that the performance of my model suffers.
Is there a different implementation method that would perform better?
Thanks!

回答(1 个)

Pramil
Pramil about 4 hours 前
Hi Paul,
The method you're using for assigning values to the elements within the “Bus Structure” involves a loop to assign values to each element of the bus, which can be relatively slow, especially for large datasets or when the function is called frequently within a simulation.
You can improve the simulation speed through the following changes:
  • Vectorize the assignment where possible. MATLAB is more efficient at handling vectorized operations.
  • Minimize the overhead of type conversion functions (like Boolean and Int32) if they're not strictly necessary.
Here is an example code for the above:
% Assuming AInput, BInput, and CInput are already in the correct format and size
% Create a temporary structure array that mirrors the bus structure
tempStruct = struct('A', num2cell(logical(AInput)), 'B', num2cell(logical(BInput)), 'C', num2cell(int32(CInput)));
% Assign the temporary structure array to the bus in one operation
Bus.Bus_Child_1 = tempStruct;
This assumes that AInput, BInput, and CInput are vectors of the correct size and type, and it uses num2cell to convert them into cell arrays that can be used to initialize a structure array matching the bus structure. This method avoids the loop entirely but requires that the data be pre-formatted to match the bus structure.
Here is a documentation link for “num2cell” function for reference:
Hope it helps.

类别

Help CenterFile Exchange 中查找有关 Interactive Model Editing 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by