Dynamic input data for plot() in MATALAB - matlab

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

Related

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

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

Plotting using scalar values. (vector/matrix/array input arguments are not accepted by code.)

I'm having a bit of trouble trying to make a 2D plot of a function depending on only one variable. Cutting a long story short, the function can only accept scalar values; it will not accept vectors. Hence it is not possible to use, for example, plot(vector, function(vector)), for a range of independent values vector. I've tried to use loop also, but my knowledge is limited, and it hasn't worked in any case.
To summarise: I want to plot function(x) vs x, however function may only have a scalar input, so taking x=-10:1:10 and then plotting it against function wouldn't work.
Can anybody point me in the right direction?
vector = -10:10 % set up your vector
output = zeros(size(vector); % initialise the output
for ii = 1:numel(vector)% loop over all elements of your vector
output(ii) = function(vector(ii)); % feed the function a single element at a time
end
plot(vector,output) % Now you can plot the two vectors

Creating a number of figures dependent on user input

I'm fairly new to Matlab so any help would be appreciated.
I'm trying to write a function using simple logic operators to create a number of 2D scatter graphs, the problem I've been having is that I cannot work out how to use a input from the user (the number of figures) to actually create that number of figures.
*edit (Just for the sake of clarity I'm plotting multiple sets of data ie columns on each figure but the important bit is that there will be multiple figures as the user specifies how many figures they want, this is the bit I cannot understand. I understand how to use hold on to plot more than one graph on each figure but how do I vary the number of figures depending on the input of the user?)
The user inputs are a matrix with dimensions 4000x30 (this will remain constant for my use) and the number of figures (this will change from 1-30) to plot from this data set. Each column represents a different sensor so the columns represent 1 set of data each.
The simpler the answer the better as I'm not a very experienced coder.
Thanks
GibGib
See if this works for you:
Data = rand(40,30); %// Just a small data set for testing.
%// Ask user how many figures are desired
prompt = {'Enter desired number of figures:'};
dlg_title = 'Input';
num_lines = 1;
def = {'5'};
NumFigures = inputdlg(prompt,dlg_title,num_lines,def);
%// Get # of figures. If the entry is not valid (i.e. remainder of division 30/entry is not 0), ask again.
while rem(size(Data,2),str2double(NumFigures{1})) ~= 0
NumFigures = inputdlg(prompt,dlg_title,num_lines,def);
end
NumFigures = str2double(NumFigures{1}); %// Convert to number
ColPerFig = size(Data,2)/NumFigures; %// Number of columns to plot per figure
ColStart = 1:ColPerFig:size(Data,2) %// Indices of the starting columns to plot
ColStart looks like this:
ColStart =
1 7 13 19 25
So its easier in the loop to index into Data and fetch the appropriate values.
%// Plot
for k = 1:NumFigures;
hFig(k) = figure;
plot(Data(:,ColStart(k):ColStart(k)+ColPerFig-1));
end
Ok, it seems like what you are asking is that you have this data matrix M, where the user defines U, and you to plot U number of plots where each plot is the 2D scatter of U columns that corresponds to M?
in that case, will this do?
figure;
hold on %is optional depending how you want your plot
for i = 1:U
plot(M(:,i))
end
If this is not what you are looking for, please specify your question further.

assigning values to a few cells from a vector

I have a cell array and a vector, and I want to assign each coordinate of the vector to a different cell, in the same location.
For example, the j coordinate in a vector becomes the (k,l) coordinate in the (j,1) cell. In pseudo matlab it would look like this:
myCell{:,1}(k,l)=myVector;
Is there a good way to do that without just looping? (performance is an issue.)
a small example:
myCell=cell(2,4);
myV=[1;2];
%what I wish to change:
for j=1:size(myV,1)
myCell{j,1}(1,1)=myV(j)
end
Thanks in advance!
Depending on the data type in your myVector you'll end up using one of the two following commands.
mat2cell or num2cell
The help pages in Matlab give great detail on the different ways to call the functions, just in case you want to do some fancy grouping of the data and such.
mat2cell: http://www.mathworks.com/help/techdoc/ref/mat2cell.html
num2cell: http://www.mathworks.com/help/techdoc/ref/num2cell.html
Sample Code:
myCell=cell(2,4);
myV=[1;2];
% %what I wish to change:
% for j=1:size(myV,1)
% myCell{j,1}(1,1)=myV(j)
% end
myCell(:,1) = num2cell(myV);

apply matrix randomisation without for loop in matlab

A question about matlab and randomisation of a 3d matrix respecting the rows and columns.
I have a n x n x s matrix M and I want to mess it up a bit, but with some control.
I can achieve my wish with a for loop
for j=1:size(M,3)
r=randperm(size(M,1));
random_M(:,:,j)=M(r,r,j);
end
Is there a way to perform this without having to loop over j? I need many randomisation iterations and could afford the benefits of indexing.
Cheers!
edit: Some more thoughts following Alexandrew's comments
I have created a function that randomises a squeezed version of M:
function randomMat=randomiseMat(Mat)
[rows,cols]=size(Mat);
r=randperm(rows);
randomMat=Mat(r,r);
then, using arrayfun I seem to get what I want:
randomM=arrayfun(#(x) randomiseMat(M(:,:,x)),1:size(M,3),'UniformOutput', false)
however, randomM is now a cell array of size (1,size(M,3)) with each cell containing randomised array.
Is there a way to make it in a 3d matrix just like the input M?
You can calculate all the values for r in one go, and then use arrayfun:
[nRows,nCols,nPages] = size(M);
[~,r]=sort(rand(nRows,nPages));
%# you should test on a realistic example whether a for-loop
%# isn't faster here
outCell = arrayfun(#(x) M(r(:,x),r(:,x),x), 1:nPages,'UniformOutput',false);
randomM = cat(3,outCell{:});