How can I write looping data matrix into same excel file? - excel

I have a looping data matrix in matlab, and I want to write it into same excel file. If I use the xlswrite('name.xls', M) it'll make a 'name.xls' excel, contained one matrix (value of the last looping). How can I write all my looping matrix (lets say it has 10 matrix with 13 columns) in one file excel and that excel file will contain all my matrix with 13 columns (so there'll be 10 rows with 13 columns). Please help, Thanks. -Machmum

In each loop iteration add your newest vector to a single matrix. Then only after the loop, write this matrix to a .xls file:
M = zeros(10,13); %// Pre-allocation like this is essential for speed
for k = 1:10
... %Your code
M(k,:) = ... %//Put your new 1-by-13 vector that you create each iteration here
end
xlswrite(file_name, M)

Although it would be better to create the matrix first and then write it in one go as Dan has suggested, it is possible to specify where xlswrite starts writing, which allows you to append data to existing files. If only specifying a start location, you must also give xlswrite a sheet name. This will be slower than pre-calculating the matrix and then just calling xlswrite once, though.
Simple example:
M = 1:10;
for n = 1:10
t = sprintf('A%d',n); % starting cell A1 through A10
xlswrite('testdata.xls',M*n,'Sheet1',t); % writes one row
end

Related

Making a vector out of excel columns using python

everyone...
I just started on python a couple of days ago because I require to handle some excel data in order to automatically update the data of certain cells from one file into another.
However, I'm kind of stuck since I have barely programmed before, and it's my first time using python as well, but my job required me to find a solution and I'm trying to make it work even though it's not my field of expertise.
I used the "xlrd library", imported my file and managed to print the columns I'm needing... However, I can't find a way to put those columns into a matrix in order to handle the data like this:
Matrix =[DataColumnA DataColumnG DataColumnH] in the size [nrows x 3]
As for now, I have 3 different outputs for the 3 different columns I need, but I'm trying to join them together into one big matrix.
So far my code looks like this:
import xlrd
workbook = xlrd.open_workbook("190219_serviciosWRAmanualV5.xls");
worksheet = workbook.sheet_by_name("ServiciosDWDM");
workbook2 = xlrd.open_workbook("Potencia2.xlsx");
worksheet2 = workbook2.sheet_by_name("Hoja1");
filas = worksheet.nrows
filas2 = worksheet2.nrows
columnas = worksheet.ncols
for row in range (2, filas):
Equipo_A = worksheet.cell(row,12).value
Client_A = worksheet.cell(row,13).value
Line_A = worksheet.cell(row, 14).value
print (Equipo_A, Line_A, Client_A)
So I have only gotten, as mentioned above, the data in the columns which is what I'm printing which you can see.
What I'm trying to do, or the main thing I need to do is to read the cell of the first row in Column A and look for it in the other excel file... if the names match, I would have to validate that for the same row (in file 1) the data in both the ColumnG and ColumnH is the same as the data in the second file.
If they match I would have to update Column J in the first file with the data from the second file.
My other approach is to retrieve the value of the cell in ColumnA and look for it in the column A of the second file, then I would make an if conditional to see if ColumnsG and H are equal to Column C of 2nd file and so on...
The thing here is, I have no idea how to pin point the position of the cell and extract the data to make the conditional for this second approach.
I'm not sure if by making that matrix my approach is okay or if the second way is better, so any suggestion would be absolutely appreciated.
Thank you in advance!

append cell row to matrix

I'm reading an excelfile in matlab with
[NUM,TXT,RAW]=xlsread(DATENEXCEL,sSheet_Data);
In the excelfile are different datamatrices in different sheets in the following form
Date Firm1 Firm2 Firm3 ...
1.1.16 12 12 12
... ... ... ...
Currently I'm handling the pure data with the NUM object and the header row with the TXT object. My first issue is how to combine the header row with the data rows. Looping does not work, since I predefine the data matrix with
daten=zeros([length(sDatesequence) size(RAW,2)]);
because I want to be able to add more data from different sources to that object. Predefining with zeros, however, leads Matlab to expect doubles and not characters. Converting the cell array TXT with cell2mat delivers unsatisfying results:
cell2mat(TXT(1,:))=Firm1Firm2Firm3...
hence only a long string vector.
Question: Is there another way to combine character vectors and double matrices?
Regards,
Richard
You can combine them in a cell array.
c{1,1} = 'Firm1';
c{1,2} = datavector;
c{2,1} = 'Firm2';
c{2,2} = datavector;
But as far as I know it is not possible to add text headers to a numerical matrix, unless you do something with typcasting. But I would not recommend that.
d(1:8)='Firm1 '; %must have exactly eight characters (a double has a length of 8 bytes)
y = typecast(uint8(d),'double') %now you have a number that would fit in a matrix of doubles
x=char(typecast(y,'uint8')) %now it's converted back to text

Secifying a common range for xlsread function in Matlab

I am trying to figure out how to specify a common range for xlsread() function in matlab.
Usually I use n=xlsread('filename','#sheet','A1:A10'), but I have quite a bit of data in the same sheet and I'd like to know if I can specify it with one range, i.e . if all my data is between '1:10', I want to specify 1:10 as range, and only call the letter values of each column.
I was thinking to do it as follows:
function [a,b,c]=getdata(filename,'1:10')
a=xlsread(filename,1,'A:A'???)
b=xlsread(filename,1,'B:B'???)
c=xlsread(filename,1,'C:C'???)
end
After some research I could not find any information as to how this is done.
Thanks in advance,
Greg
If you want to read 1 to 10 rows of column A, use:
data = xlsread(filename, 1, 'A1:A10');
If you want to read 1 to 10 rows of all columns, use:
data = xlsread(filename, 1, '1:10');
If you want to read 1 to 10 rows of, say, first three columns A, B, and C, use:
data = xlsread(filename, 1, 'A1:C10');
Using dynamic variable names is always a bad idea. Read this for explanation. But if you still want to create a, b, and c and so on depending on the number of columns in the Excel file, you can use:
for k=1:size(data,2)
assignin('caller', char(96+k), data(:,k)); %or char(64+k) for block letters
end
The above will work if number of columns are less than or equal to 26. This may only be feasible if you're dealing with a few columns. But I still recommend to avoid it.

matlab multidimensional array to excel

I have a Matlab script with an output of a multidimensional array LCOE (3 dimensions) of size 16:12:34. This output needs to be written to Excel, therefore I use xlswrite.
I have tried this:
T = LCOE(:,:,1);
xlswrite('filename', T, 'sheetname', 'B2');
This does what it's supposed to, but only writes one table to excel, and I would like to write all 34 tables to excel underneath each other, spaced by `2 blank rows.
Then, I tried this:
for y = 1:34
T = LCOE(:,:,y)
xlswrite('filename', T, 'sheetname', strcat('B', num2str(2+(y-1)*18)));
This works, but is very slow, since matlab writes each table separately to excel. Is there a faster way to do this?
Instead of using xlswrite again and again. Dump all the values of a 3D matrix into a 2D matrix and add rows of NaNs so that when you write that to excel file, you get 2 blank rows.
Following code improves the execution time by the factor of more than 10.
LCOE = 100*rand(16,12,34); % Taking random values for LCOE
T = NaN(18*34-2 ,12); % 1. Pre-allocation 2. 16+2 = 18
% Following loop dumps all the values of 3D matrix into a 2-D followed by 2 rows of NaN
% to leave 2 blank rows in excel file.
for k = 1:34
T(18*(k-1)+[1:16], :) = LCOE(:,:,k);
end
xlswrite('filename', T, 'sheetname', 'B2'); % Writing the Excel file
In my system, my code takes about 1 second to execute while your code takes about 10.5 seconds. So that's a significant difference.

write information into Excel after each loop

I have a 6x7 matrix(A) and some operation I'm doing on it for k=1:50 (number of loops).
I know that in order to write a single matrix in an excel file I need:
xlswrite('Filename.xls', A, 'A1')
How is it possible to write the information after each loop, in that way that each loop starts at position A1+((k-1)*6+1) in Excel and I have all results of Matrix(A) listed one after each other.
Thank you!
When using the XLSWRITE function, you can avoid having to compute Excel cell ranges each time, by specifying both sheet number and range, where range only gives the first cell to start at.
It is especially useful if the matrix changes size each iteration; we simply take the last cell used and shift it by the number of rows of the matrix.
Example:
offset = 1;
for i=1:5
%# generate different size matrices each loop
A = ones(randi(4),randi(4)).*i;
%# insert matrix in Excel inside the 1st sheet, starting at cell specifed
xlswrite('filename.xls', A, 1, sprintf('A%d',offset));
%# increment offset
offset = offset + size(A,1);
end
this creates an Excel file with the following content:
1 1
1 1
1 1
2 2 2 2
3 3
3 3
4
4
4
4
5 5 5
5 5 5
5 5 5
5 5 5
Note that a connection is made to Excel then closed each time XLSWRITE is called. This has a significant overhead.
A better approach would be to open Excel once, and reuse the same session to write all of your data, then close it once we are done. However, you will have to call the Office Interop functions yourself.
Since the trick I mentioned above won't work now, I will be using the "Calculate Excel Range" function to compute the cell ranges (there are many other implementations of FEX).
Here is the code (reusing some code from a previous answer):
%# output file name
fName = fullfile(pwd, 'file.xls');
%# create Excel COM Server
Excel = actxserver('Excel.Application');
Excel.Visible = true;
%# delete existing file
if exist(fName, 'file'), delete(fName); end
%# create new XLS file
wb = Excel.Workbooks.Add();
wb.Sheets.Item(1).Activate();
%# iterations
offset = 0;
for i=1:50
%# generate different size matrices each loop
A = ones(randi(4),randi(4)).*i;
%# calculate cell range to fit matrix (placed below previous one)
cellRange = xlcalcrange('A1', offset,0, size(A,1),size(A,2));
offset = offset + size(A,1);
%# insert matrix in sheet
Excel.Range(cellRange).Select();
Excel.Selection.Value = num2cell(A);
end
%# save XLS file
wb.SaveAs(fName,1);
wb.Close(false);
%# close Excel
Excel.Quit();
Excel.delete();
In fact, I ran both version with 50 iterations, and compared timings with TIC/TOC:
Elapsed time is 68.965848 seconds. %# calling XLSWRITE
Elapsed time is 2.221729 seconds. %# calling Excel COM directly
I think that xlswrite will overwrite an existing file, so you're better off gathering all the data, then writing it in one go. Also, writing it all in one go will be faster since it involves opening and closing Excel only once.
However, if you really want to write it in a loop, the following should work (assuming you mean going down):
range = sprintf('A%i:G%i', (k-1)*6+[1 6]);
xlswrite('Filename.xls', A, range);
Note that this won't adjust automatically if A changes size.

Resources