Using Matlab writematrix in several scripts to write to the same csv - matlab

To analyse some data I have severral scripts that take the same input and calculate different things. I would like to have matlab then write the output of each script to the same csv so I have all the outputs in one place. How do I do this? Is this even possible w/o making a huge matrix in Matlab and writing the whole matrix in one comaand? As far as I can tell writematrix only ever writes to the first column.
Example:
A = rand(1,10)'; B = rand(1,10)';
writematrix(A,'M.xls') %write to column 1 of csv
writematrix(B,'M.xls') %this overwrites the previous command
You can write to different sheets in xcel, but that's not suitable.
The documentation for writematrix is here: https://uk.mathworks.com/help/matlab/ref/writematrix.html
TIA

Specify the range (or the starting cell) for second column using the 'Range' property and use 'append' for WriteMode as shown below:
A = rand(10,1); B = rand(10,1);
%Side-note: ' is complex conjugate transpose.
%Use transpose .' when you want to take transpose
%In this case, you can initialise the random matrices with 10x1 size
%instead of 1x10 size and then taking the tranpose
writematrix(A,'M.xls');
%Assuming that B1 is the starting cell for the second column:
writematrix(B,'M.xls','Range','B1', 'WriteMode', 'append');

Related

Script to print data into plain text file

x=-1:1;
y=-2:2;
f(x,y)=1-x^2-y^2
I want to print the data into a text file with 3 columns: one for x, one for y and one for f(x, y)=1-x^2-y^2. There should be 20 data points for x, and 40 for y.
Presuming you mean a solution on a 21-by-41 points grid you'd need this:
x=-1:.1:1;
y=-2:.1:2;
[xx,yy] = meshgrid(x,y); % create grid for file
f=1-x.^2-y.'.^2; % use broadcasting to calculate
totaldata = [xx(:) yy(:) f(:)]; % concatenate into single matrix
fid = fopen('mydat.txt','w') ; % open file
fprintf(fid,'%f %f %f \n',totaldata); % write data
fclose(fid); % close file
I'd strongly suggest you to read The MathWork's own tutorial; not because writing to file is so easy, but because what you wrote up there gives you lots of errors. The first is
f(x,y)=1-x^2-y^2
Error using ^
Inputs must be a scalar and a square matrix.
To compute elementwise POWER, use POWER (.^) instead.
So, using elementwise POWER, as suggested:
x=-1:.1:1;
y=-2:.1:2;
f(x,y)=1-x.^2-y.^2
Matrix dimensions must agree.
Thus more work is needed. These are basic MATLAB indexing and matrix operations, which is what the entire software is build on. Hence the suggestion to take their own tutorial, or take a course in MATLAB.

Dynamic input data for plot() in MATALAB

I have text files that contain two columns with numbers. Over a for loop, I store the first and second column as X(n) and Y(n) respectively (as floats), n being the iteration number.
Let's say that I don't know how many files I have and that the length/range of the data is variable.
Is there a way to create a sort of dynamic variable so I can use it as an input to graphically represent the data like
plot(dynamic_variable)
instead of writing per hand
plot(X1,Y1,X2,Y2,...,XN,YN)
I know there should be the possibility to interpolate the data (since the files haven't the same length/range) so it is possible to create two matrices, let say XM and YM, and finally write (XM,YM), where
XM = [X1_intrpl X2_intrpl ... XN_intrpl]
YM = [Y1_intrpl Y2_intrpl ... YN_intrpl].
Is there a more direct way to do it?
I am far from being an expert: so I would also appreciate any comment and/or criticism on my idea/approach.
The Matlab plot function does not seem to support what you are looking for. I guess you have already checked the documention on the plot command here:
https://de.mathworks.com/help/matlab/ref/plot.html?requestedDomain=www.mathworks.com
What you can do is write your own plot function that takes both matrices as parameters.
In the function you would loop over the pairs in the matrices plotting them using hold on to display all the data in one plot.
One option would be reading in each set of X(n) and Y(n) into a cell array such that,
X{1} = X1
Y{1} = Y1
...
X{N} = XN
Y{N} = YN
Then to plot, rather than trying to merge everything into a single array, you can simply plot each set of X and Y one at a time onto the same figure.
%Instead of:
%plot(X1,Y1,X2,Y2,...,XN,YN)
%Use:
figure()
hold on
for i=1:N
plot(X{i},Y{i})
end

How to create a submatrix extracting each raw from a matrix that satisfy a logical condition?

I have a single *.txt file with multiple records, from an MPU6050 connected to Arduino.
I can recognize when a new record was made because the column time restart from a random value lower then the previous (is never 0).
The file is a nX7 which contains in order time, ax, ay, az, gx, gy, gz
I am trying to extract the m subrecords from the single matrix, so i defined a logical if.
If time i > time i+1 keep track of the position from the original matrix and store in a submatrix (rangematrix) this boundary values.
From the rangematrix create a set of submatrices (the total number of submatrices will be [size(rangematrix,1)-1] .
I have a civil engineer background and i am a noob with Matlab.
Thanks for your time, thanks for you patience.
I tried to solve this with the code below, but I think is only rubbish.
%Open the file
filename= uigetfile ('.txt');
fileID = fopen (filename);
logmpu6050 =csvread(filename);
fclose (fileID);
n=length(logmpu6050);
%Count every time i>i+1 where i is the i,1 element of my dataset
for i=1:n-1
%Save the data of the i raw every time happens i>i+1
if logmpu6050(i,1)>logmpu6050(i+1,1);
rangematrix(i,:)= logmpu6050(i,:);
end
end
% Create a new sets of matrices from boundary values
I also read a lot of questions on stack but i didn't find the solution:
MATLAB: extract every nth element of vector
Extract large Matlab dataset subsets
MATLAB: Extract multiple parts of a matrix without using loops
MATLAB: Extracting elements periodically
Extract data from MATLAB matrix without for-loop
How to extract a vector from a large matrix by index in MATLAB?
How to extract a part of a matrix with condition in Matlab
You can use diff.
filename= uigetfile ('.txt');
fileID = fopen (filename);
logmpu6050 =csvread(filename);
fclose (fileID);
n=length(logmpu6050);
%Count every time i>i+1 where i is the i,1 element of my dataset
rangematrix = logmpu6050(diff(logmpu6050(:,1)) > 0,:);

Check for row or column vector in matlab

I have a function that processes a row vector. I want to make it generic for any type of input vector. Be it column or row.
One solution i thought is to preserve the existing implementation and check for the input vector for column or row type.
How can i perform this check?
iscolumn() or isrow() functions do not work here!
First, verify that the input IS a vector. isvector can help here. Or, use size, or any of a number of various artifices.
Second, convert your vector to a column vector.
vec = vec(:);
Third, write your code to always expect a column vector, since vec(:) does that.
Finally, save the original shape of your vector and reshape any output vector expected to be the same shape as the input. So your final code should look vaguely like this...
% test for errors
if ~isvector(vec)
error('The sky is falling')
end
% convert to column form always
vecshape = size(vec);
% process the vector
outputvec = ... % do stuff here
% reshape the output to be the same shape as the input
outputvec = reshape(outputvec,vecshape);
Check the size of the vector using size - if it has one column and many rows, your function can call itself with the transposed variant.

What is the ' (single quote) operator in MATLAB?

I've got some examples on how to use a government-supplied library file, but the examples are written in MatLab. Our project is in C#.
Could someone tell me what this means?
fid = fopen('d:\coilmodel\outlet.txt');
M = fscanf(fid, '%f', [7, inf]);
fclose(fid);
M = M';
I understand I am opening a text file and using that to populate a matrix M that is 7 floating points wide, then it closes the file.
What is M = M';?
I can duplicate all of this in my C# code except for the last line, and my only hurdle is I do not know what the action is doing.
Is this a transform?
Is the matrix being transposed?
I'd like to get a reference to this action so I can do further research.
It is the complex conjugate transpose (or adjoint) of the matrix M, see here.
Note
As Edric specified, ' it's the CTRANSPOSE, i.e. the “adjoint matrix or (complex) conjugate transpose”, which gives the same result when applied on real matrices, but on complex matrices
negates the sign of the imaginary part of the complex elements in A
If you need only to
interchanges the row and column index for each element
then you will use .'.
Note that ' is the CTRANSPOSE operator in MATLAB. If you don't want the complex conjugate, use .' which is the TRANSPOSE method.