convert struct type to matrix octave - matlab

I have a myfile.mat that contains 3000x35 size data. When I load it into a variable as :
a = load('myfile.mat')
It gives struct of size 1x1 . How can I get exact form as matrix. This is required because I need to change certain column values.

(This answer is valid for MATLAB, I am not sure it works exactly the same way in Octave)
You have several options:
Option 1:
If the .mat file only contains one variable, you can do:
a = struct2array(load('myfile.mat')); % MATLAB syntax
a = [struct2cell(load('myfile.mat')){:}]; % Octave syntax
Option 2:
You need to know the name of the variable at the time of saving, which is now a name of a field in this struct. Then you would access it using:
a = load('myfile.mat'); a = a.data;
Option 3 (unrecommended!):
Just remove the a = part of the expression,
load('myfile.mat');
Then the variables inside this file will "magically spawn" in your workspace. This is not recommended because it makes it difficult (impossible?) to see when certain variables are created.

I found the solution myself. I did like this
a = load('myfile.mat')
a = a.data
So that now I can access values of a as matrix with indexing, a(1,2) like this.
It is in octave. I hope it is similar in matlab.

Related

How to read .mat output files in JModelica?

To save the time, I'm trying to read the .mat file rather than simulate the model again.
I used scipy.io.loadmat but it didn't work well:
res = loadmat('ChatteringControl_result.mat')
res.keys()
['Aclass', 'dataInfo', 'name', 'data_2', 'data_1', 'description']
The keys are not variable names, and I don't know how to get the variable values.
Then I searched for resolutions, and found DyMat, it works well for other variables but cannot get time.
res1 = DyMat.DyMatFile('ChatteringControl_result.mat')
T = res1['T']
t = res1['time']
KeyError: 'time'
So, how can I get all the results in JModelica?(Without open Matlab of course.)Like, a built-in function in JModelica?
BIG THANKS!
To load the mat file using JModelica you can use this code:
from pyfmi.common.io import ResultDymolaBinary
res = ResultDymolaBinary("MyResult.mat")
var = res.get_variable_data("myVar")
var.t #Time trajectory
var.x #Variable trajectory
https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/technical_details.html#the-matv4-result-file-format describes the format. I think you can also look in a Dymola manual for more details.
As for DyMat, there is no reason to get the time trajectory because you typically lookup what value a variable has at a certain time. The start and stop-times are in the data_1 matrix as far as I remember (or typically get it from the first trajectory in the data_2 matrix). (The data_2 matrix may be interpolated, so the time values stored in it may not reflect the actual steps taken internally by the solvers)

Dynamically labelling in MATLAB

I have a MATLAB script which creates an matrix, 'newmatrix', and exports it as matrix.txt:
save -ascii matrix.txt newmatrix
In my script I also calculate the distance between certain elements of the matrix, as the size of the matrix depends on a variable 'width' which I specify in the script.
width = max(newmatrix(:,5)) - min(newmatrix(:,5))
x_vector = width + 2
And the variable x_vector is defined as width + 2
I want to know is it possible to export x_vector, labelling it as, eg my_vector $x_vector so that "my_vector 7.3" will be produced when the value of x_vector is equal to 7.3
I have tried:
save -ascii 'my_vector' + x_vector
But receive the following errors:
warning: save: no such variable +
warning: no such variable 'my_vector'
Three things:
1) I prefer to use functional form of the calls so that you can pass in variables rather than static strings.
save -ascii matrix.txt newmatrix
is equivalent to:
save('-ascii','matrix.txt','newmatrix')
In other words, in the first form all inputs get treated as string inputs to the function.
2) You can't add character arrays in Matlab. Rather you concatenate them or use sprintf.
name = sprintf('my_vector_%g',x_vector);
save('-ascii',name)
Note by using the functional form we can now pass in a variable. Note however this won't work because name should be either a valid option or a variable, and my_vector_7.3 isn't either.
3) I'm not entirely sure what you're asking, but I think you want the text file to say "my_vector 7.3". I don't think -ascii supports strings .... You could write something using fprintf.
fid = fopen('matrix.txt','w');
fprintf(fid,mat2str(new_matrix));
fprintf(fid,'\n');
fprintf(fid,'my_vector %g',x_vector);
fclose(fid);

save part of matlab cell array, proper refence

I found the following piece of MATLAB code previously posted by someone here:
x = cell(3,4);
save x;
matObj = matfile('x.mat','writable',true);
matObj.x(3,4) = {eye(10)};
It creates a .mat file with a 3x4 cell array in it, and the content of the cell positioned at (3,4) is a 10x10 identity matrix.
What would be the right syntax to read the .mat file and change the value of the element positioned at (2,3) in the identity matrix to say -5?
If it were possible to use the curly braces I would do it as mat.Obj.x{3,4}(2,3)=-5, but MATLAB says this type of referencing for cell arrays is not supported.
Thanks in advance.
From what I know, there is no way in matlab to reference matlab.io.MatFile objects like you want. The easier way would be just to create a temporary variable to do it.
Thus instead trying to do this:
matObj.x(3,4) = {eye(10)};
matObj.x{3,4}(2,3)=-5; % this will lead to error, as you noticed
do like this:
tmpVar = eye(10);
tmpVar(2,3) = -5;
matObj.x(3,4) = {tmpVar};

MATLAB uint8 data type variable save

does anyone know how to save an uint8 workspace variable to a txt file?
I tried using MATLAB save command:
save zipped.txt zipped -ascii
However, the command window displayed warning error:
Warning: Attempt to write an unsupported data type to an ASCII file.
Variable 'zipped' not written to file.
In order to write it, simply cast your values to double before writing it.
A=uint8([1 2 3])
toWrite=double(A)
save('test.txt','toWrite','-ASCII')
The reason uint8 can't be written is hidden in the format section of the save doc online, took myself a bit to find it.
The doc page is here: http://www.mathworks.com/help/matlab/ref/save.html
The 3rd line after the table in the format section (about halfway down the page) says:
Each variable must be a two-dimensional double or character array.
Alternatively, dlmwrite can write matrices of type uint8, as the other poster also mentioned, and I am sure the csv one will work too, but I haven't tested it myself.
Hopefully that will help you out, kinda annoying though! I think uint8 is used almost exclusively for images in MATLAB, but I am assuming writing the values as an image is not feasible in your situation.
have you considered other write-to-file options in Matlab?
How about dlmwrite?
Another option might be cvswrite.
For more information see this document.
Try the following:
%# a random matrix of type uint8
x = randi(255, [100,3], 'uint8');
%# build format string
frmt = repmat('%u,',1,size(x,2));
frmt = [frmt(1:end-1) '\n'];
%# write matrix to file in one go
f = fopen('out.txt','wt');
fprintf(f, frmt, x');
fclose(f);
The resulting file will be something like:
16,108,149
174,25,138
11,153,222
19,121,68
...
where each line corresponds to a matrix row.
Note that this is much faster than using dlmwrite which writes one row at a time

How to save data using matfile Matlab

New to matlab and I need some help.
I need to create a .mat file , using matObj or save(), that has some information that will be passed from some variable. Lets say that variable x = 1,2,3,4,5
1|2|3|4|5|
Then I need to save that in test.mat
Then I need to load that file and save something like,
6|7|8|9|10|
So I get
1|2|3|4|5|
6|7|8|9|10|
and so on.
So every time I save it goes to a new row. The numbers that go inside they are not random the above numbers are just there to make things simple to see.
Can someone help me out.
You are describing two different problems here. The first is saving and loading of data.
Saving is easy:
x = 1:5;
filename = 'myFile.mat'
save(filename, 'x'); %notice that I used the string name of the variable
Likewise loading is also simple:
filename = 'myFile.mat';
data = load(filename); % loaded variables are placed in a struct to prevent overwriting workspace variables
x = data.x;
The 2nd problem can be solved using concatenation:
lets say you want to convert the vector 1 2 3 into the matrix:
1 2 3
1 2 3
You can simply call:
v = 1:3;
m = cat(1, v, v);
Likewise you can add an additional row to the existing matrix using the same command:
m = cat(1, m, v);
I'm sure any amount of googling will get you how to save a variable to a mat file - The matlab docs are absolutely spectacular, and such a simple operation will be covered along with examples showing exactly how to use the functions.
As for the second part, use the concatenation property
new = [old1 old2];
to concatenate horizontally, and
new = [old1;old2];
to concatenate vertically. Then resave the same way that you just learned via google.
Hope this helps, and in the future, i guarantee 99% of the answers to a new user's questions will be in the top two google search results if you append "matlab" to your search. The Mathworks really set the bar on documentation in my opinion. (Of course, I last used MATLAB 3 years ago)