How to convert datatype of all fields of struct in MATLAB to double? - matlab

I have a struct in matlab called mystruct
It has the following fields with the following classes:
Field Class
a single
b single
c double
I want to convert all fields of mystruct to class double, but when I try:
double(mystruct)
I get the following output from MATLAB:
??? Error using ==> double
Conversion to double from struct is not possible.
Futhermore, I am giving mystruct as just an example. I realize I could just individually cast each field manually since there are only 3 fields in this example. I am wondering how do this this conversion to double for any structure in matlab with many fields and subfields.

For scalar structs (numel(mystruct) is 1) the answer of Luis Mendo is probably the best solution. For other structs use this code:
cell2struct(cellfun(#double,struct2cell(mystruct),'uni',false),fieldnames(mystruct),1)
It converts the struct to a cell, then converts each element to double and converts back to a struct.

You can use structfun for that:
mystruct = structfun(#double, mystruct, 'uniformoutput', 0);

Related

Create a fixed size 3 dimensional array of type string

I am trying to create a fixed size 3 dimensional array in Swift with datatype of string like this:
var 3dArray:[[[String]]] = [[[50]],[[50]],[[50]]]
But it is giving error:
Cannot convert value of type 'Int' to expected element type string
From your question title you are trying to create 3d array with datatype [[[String]]] and in your question detail you are assigning it an Int value which is not possible in swift. That's why you are getting an error. Because your 3dArray object is expecting a String values
Either you can assign String values this way:
var yourArr: [[[String]]] = [[["50"]],[["50"]],[["50"]]]
Or if you want to make Int array you can do it this way:
var yourArr: [[[Int]]] = [[[50]],[[50]],[[50]]]
Note:
As #Martin R suggested variable names cannot start with a digit.
There is no typical way of creating multidimensional arrays in Swift.
But, you can create an array which will contain only String arrays and then append 3 different String arrays. Please find the code below:
var array = [[String]]()
array.append([String]())
array.append([String]())
array.append([String]())
At the end your array will be looking this way:
[[], [], []]
Or you can just create same array this way:
var array:[[String]] = [["50"],["50"],["50"]]
But keep in mind, "50" are strings which are content of those arrays and not their size.
If you want to have a fixed-size array, then you have to use some third party solutions like this one.

Matlab: iterate over multiple structs

I have 5 Matlab structs. I would like to iterate over them. My current solution is the following:
all_structs = [struct1,struct2,struct3,struct4,struct5];
for single_struct = all_structs
% do stuff to each struct here
end
However, each of the structs above has a matrix with a lot of data (including some other properties). Also, whatever I change in the single_struct is not passed back to the original struct.
Question: How do I fix that? Does Matlab copy all that data again when I create the vector all_structs? Or is the data from each of the structs (struct1,...,struct5) passed by reference? Is there a better way to iterate over multiple structs?
Thanks for helping!
struct will not be passed by reference. You will need to loop over the elements in all_structs using an index and then access and modify using that index. If you need something to be treated as reference you will need to define a class for it and make the class inherit from handle. Suggested reading
for i = 1:numel(all_structs)
% do stuff to each struct here
all_structs(i).data = ones(10,5); % your code here
end
I would suggest also reading on arrayfun, though it is useful if you want to do an operation and get results. From your description it sounds like you want to modify the structs.
In case you want to modify content of original structs, without making a copy, you can use a cell array of structs names.
Then iterate the names, and use eval to modify the content.
Using eval is inefficient, so don't make it a habit...
See the following code sample:
%Create sample structs (each struct has a data element).
struct1.data = 1;
struct2.data = 2;
struct3.data = 3;
%Create a cell array containing structs names as strings.
struct_names = {'struct1', 'struct2', 'struct3'};
%Iterate all structs names
%Modify data elements of each struct using eval.
for i = 1:length(struct_names)
sname = struct_names{i}; %Get struct name from cell array.
%Evaluate a string like: 'struct1.data = struct1.data + 1;'
eval([sname, '.data = ', sname, '.data + 1;']);
end

Convert Matlab struct array to cell array

Can a Matlab struct array be converted to a cell array without iterating through the array?
I want each struct in the struct array to become one cell in the cell array. The command struct2cell doesn't seem to do it as it breaks out each field in the struct into a separate cell.
This has been posted to:
Convert Matlab struct array to cell array
http://groups.google.com/forum/#!topic/comp.soft-sys.matlab/xIOTcs5HPeg
Try num2cell:
myStructCell = num2cell(myStruct);
For example:
>> myStruct(1).name = 'John';
>> myStruct(2).name = 'Paul';
>> myStruct
myStruct =
1x2 struct array with fields:
name
>> myStructCell = num2cell(myStruct)
myStructCell =
[1x1 struct] [1x1 struct]
>> myStructCell{1}
ans =
name: 'John'
>> myStructCell{2}
ans =
name: 'Paul'
>> myStructCell{2}.name
ans =
Paul
Actually, I don't think that what I'm trying to do is necessary. Let me explain, in case it saves someone else from going down the same path.
The motivation for the above is that I want to extract a certain subfield from all structures in the struct array and have it in the form of a comma separated list:
myStruc(1).fieldX.subfieldA, ...
myStruc(2).fieldX.subfieldA, ...
myStruc(3).fieldX.subfieldA
I knew that I could generate a comma separated list by indexing into all cells into a 1D cell array via myCellArray{:}.
However, I found that there was actually an entire help page entitled "Comma-Separated Lists" showing that structs behave in the same way. So the above comma separated list is equal to myStruc(:).fieldX.subfieldA.
In fact, converting the struct array into a cell array wouldn't have worked because you can't use dot-indexing to access the fields after curly-brace indexing of the cell array. For example, if there was a vectorized way to convert myStruct(i) into myCell(i), I was hoping to be able to generate
myCellArray{1}.fieldX.subfieldA, ...
myCellArray{2}.fieldX.subfieldA, ...
myCellArray{3}.fieldX.subfieldA
via the expression myCell{:}.fieldX.subfieldA. The dot-indexing after the curly braces is a syntax error.
Lesson learned: Use struct array indexing directly to enable access to the struct fields & subfields.
***** CAVEAT *****
I only tested the generation of comma separated lists using multiple levels of dot-indexing combined with a scalar numerical array index, e.g., myCellArray{2}.fieldX.subfieldA. It doesn't work when with a vector numerical index in place of the scalar value 2, i.e., Matlab cannot handle myCellArray{:}.fieldX.subfieldA or myCellArray{2:3}.fieldX.subfieldA.
Oh well. :(

Pass Simulink.Parameter to C S-function

How does one pass a Simulink.Parameter structure (which, in my case, is a structure of structures) to a C S-function?
Edit:
Information on Simulink.Parameter
You can create a Simulink.Parameter object this way:
modelParameters = Simulink.Parameter;
modelParameters.Value = myStruct;
modelParameters.CoderInfo.StorageClass = 'ExportedGlobal';
The myStruct value is a regular matlab structure of structures. This is how it looks in my case:
This is a special object type for passing parameters to Simulink and I am looking for a mechanism to access it from a C S-function.
Download a MnWE from here.
Edit 2:
I read the parameters this way:
modelParameters_T *modelParameters = (modelParameters_T*)mxGetPr(ssGetSFcnParam(S, PARAM_STRUCT));
But I can see why this approach doesn't work - the structure object from Matlab is not similar to a C structure, i.e. is not contiguous in memory and contains other properties too. I think I will cast the Matlab structure to an array and then cast the array in C to my struct definition.
mxGetPr is not the right way to access your parameter which is an object type. It is not a struct type. Even if it is a struct type you need to use mxArray API to access struct fields. You need to use something like the following code to access the fields.
mxArray* param = ssGetSFcnParam(S, PARAM_STRUCT);
mxArray* prop = mxGetProperty(param, 0, "Value"); // Get Value property from param object
// If prop is double precision use the following line to get its value
double* prop = *(mxGetPr(prop));
Check out mxArray API in the doc for accessing different types of mxArrays.

C programming on IAR- timestamp Conversion to readable format

I am using Z-stack-CC2530-2.5 for developing Zigbee-based application. I've come across a timestmap conversion problem.
I am using osal_ConvertUTCTime method to convert a uint32 timestamp value to timestampStruct as follows:
osal_ConvertUTCTime(& timestampStruct, timestamp);
The Struct is defined as follows:
typedef struct{
uint8 seconds;
uint8 min;
uint8 hour;
uint8 day;
uint8 month;
uint16 year;
} UTCTimeStruct
My Question:
How to convert the Struct's content to be written on the UART port in a human readable format ?
Example:
HalUARTWrite (Port0, timestampStruct, len) // Output: 22/1/2013 12:05:45
Thank you.
I do not have the prototype of the function HalUartWrite at the moment, but I googled it and someone used it as this:
HalUARTWrite(DEBUG_UART_PORT, "12345", 6);
so I guess the second argument must be a pointer to char. You can't just pass a struct UTCTimeStruct variable into the second argument. If you just need to output the raw data to the serial port. You need to cast the struct into char * in order to make the compiler happy. But generally, this is bad practice. This might not be a problem in your case as you work in a 8-bit processor that all the struct fields are either a char or a short. In general, if you cast a struct into a char * and print it out, due to struct padding, you get a lot of nonsense characters between your struct fields.
OK. A bit off topic. Back to your question, you need to convert the struct into a friendly string yourself. Because you know your output string is of format "22/1/2013 12:05:45" which has fixed length, you can simply declare a char[] of that length. And manually fill in the numbers by bit-manipulating the uint32 timestamp value. After that, you can pass the char[] into the second argument and the exact length into the third argument.