Put Excel columns in an array Matlab - excel

I have never used Excel parser in MatLab. I have an Excel file which has 3 columns. And I would like to save all elements of column 2 in an column array and all elements of column 3 in an other column array. How can I browse the Excel file column by column and then line by line?
It works with this :
[~,~,data] = xlsread('excelfile.xlsx');
% Save columns
arraycolumn2 = data(:,2); % Parse column 2
arraycolumn3 = data(:,3); % Parse column 3

You can use function importdata
data = importdata('yourExcelFile.xlsx');
colum1 = data(:,1);
colum2 = data(:,2);
colum3 = data(:,3);

Related

Python loop through a range and print into a csv for different columns with different ranges

I have three different columns that I need to print them into a CSV which each column have a different range for each column using Python
e.g column 1 - range: 0 to 5000
column 2 - range: 450123 to 565123
column 3 - range: 125000 to 130000
Would like to print these columns into a CSV something like this
column1, column2 , column3
0,450123,125000
1,450124,125001
......
......
5000,565123,130000
import csv
header = ['column1']
with open('test.csv', 'w') as file:
writer = csv.writer(file, delimiter='\t', lineterminator='\n', )
writer.writerow(i for i in header)
for j in range(1, 500001):
row = ["martec" + str(j)]
writer.writerow(row)
I managed to get it for one column but would to print multiple columns
As scotscotmcc pointed out, the output won't be exactly as you want it. There are unequal ranges in the three columns. But assuming the columns should all have the same amount of numbers in them then something like the following should work. You just need to add all three columns to the list (row) to be written to the csv.
header = ['column1','column2','column3']
max = 5000
with open('test.csv','w') as file:
writer = csv.writer(file,delimiter=',',lineterminator='\n')
writer.writerow(header)
for i in range(0,max):
row = [ i, 450123+i, 125000+i ]
writer.writerow(row)
Output would be something like
column1,column2,column3
0,450123,125000
1,450124,125001
2,450125,125002
3,450126,125003
4,450127,125004
5,450128,125005
6,450129,125006
7,450130,125007
8,450131,125008

Read excel file and assign each coulmn a variable in MATLAB

I am having a simple problem while reading excel data which contains strings, long string, and numbers. Now I need to make each column (I have 11 here) to define separate variables of 1 column vector so that I can plot in MATLAB against each other or combination.
But the problem is the reading the file and creating 11 column vector. When I assign variable the header also comes.
Code:
%fid = fopen('Data_Link.xlsx');
[num,txt,raw] = xlsread('Data_Link.xlsx');
%fclose(fid);
% Extract data from readData
A = raw(:,1);
B = raw(:,2);
C = raw(:,6);
So I need the variables without header
Data file is truncated and given here.
Can anyone help me?
You can use readtable as ThP suggested. But if you want to use xlsread and you want your data without the header, you just need to remove the first row as in the below example:
%fid = fopen('Data_Link.xlsx');
[num,txt,raw] = xlsread('Data_Link.xlsx');
%fclose(fid);
% Extract data from readData
A = raw(2:end,1);
B = raw(2:end,2);
C = raw(2:end,6);
Note that each array will receive data from row 2 to last row.
You can use readtable instead of xlsread.
Using
T = readtable(‘Data_Link.xlsx’)
will result in a table with a variable for each column. For example T.Year would hold the values from the ‘Year’ column and T.Title would hold the values from the ‘Title’ column, etc.

Looping in Matlab to batch process Excel files

I know how to read in multiple Excel files, but am struggling to conduct the same analysis on all of those files. The analysis requires I average some values in different columns, then print those average values to a separate Excel sheet. I can do this with one Excel file, but have trouble figuring out how to print each average value in a different row in the output Excel file. Here is the code I have that works for one file (reads it, averages values in column 4, then prints to a separate Excel file):
data = xlsread('test_1.xlsx');
average_values_1 = data(:,4);
a = [average_values_1];
data_cells = num2cell(a);
column_header ={'Average Value 1'};
row_header(1,1) ={'File 1'}
output = [{' '} column_header; row_header data_cells];
xlswrite('Test Averages.xls', output);
How might I do this over and over again while printing values from each file in the output file as its own table? I suspect a nested loop is in my future.
Thanks in advance.
Here is working example of what you possibly want to do with xlswrite[‍1]:
filename = 'testdata.xlsx'; % Filename to save average values in
for k = 1:10 % Looping for 10 iterations
sheet = 2; % Selecting sheet2
Avg = randi([1 10],1,1); % Generating a random average each time the loop is run
xlRange = char(64+k); % 65 is the ASCII value of A
xlswrite(filename,Avg,sheet,xlRange); % Writing the excel file
end
This code gives the following output [‍2] :
Fig.1: Values are saved in a single row of excel file
If you want to get the output in a single column then use this xlRange = ['A',num2str(k)]; instead. It'll give you the following output [‍2] :
Fig.2: Values are saved in a single column of excel file
[‍1]: Read the documentation of xlswrite for more details.
[‍2]: Output values may vary since random integers are generated.

Pass from multidimensional array to spreadsheet

I have a multidimensional array which of the form:
where each row represents a sheet and each column represents a type of variable.
What I want to do is export the data into a spreadsheet where each row gets stored in a sheet with its columns. (Maybe it could be easier separate the sim multidimensional array into five matrices and then export those together to a spreadsheet) but I don't know if it's the most efficient way.
Here is a image of the spreadsheet:
Below is my code, which basically reads the sheets from a Excel and make a simulation of 1,000 cases for each type of data:
sim={};
for k = 1 : 5
sheet = xlsread('CB.xlsx', k);
[m, n] = size(sheet)
for i = 1 : n
[f,x] = ecdf(sheet(:,[i]));
[f, dup] = unique(f);
x = x(dup);
randomValues = rand(1, 1000);
sim{k,i} = round(interp1(f,x, randomValues));
end
end
trying to use Mikhail_Sam'answer I got the follow problems:
`sheet = 1
for i = 1:5
for j = 1:5
xlswrite('filename.xls',sim(:,i,j),sheet,strcat(char(64+j),int2str(1)))
end
sheet = sheet+1;
end`
but it says "Index exceeds matrix dimensions", then I tried this code
sheet = 1
for i = 1:5
for j = 1:size(sheet)
xlswrite('filename2.xls',sim{i,j},sheet,'A1:E1000');
end
sheet = sheet+1;
end
This code write the file ith the 5 sheets but it is filled with the first 5 numbers of each row of the multidimensional array. Then I tried to apply num2cell and run your code but it gives "index exceeds matrix dimension" again
I don't know about 'the most efficient way', but I did it this way:
for example I create 3x3x3 matrix and try to write it to excel:
sheet = 1
for i = 1:3
for j = 1:3
xlswrite(filename,x(:,i,j),sheet,strcat(char(64+j),int2str(1)));
end
sheet = sheet+1;
end
And I got what you want - 3 sheets, and data in rows.
replace 3 at your dimensions. But I have one weak place - I don't remember numeric mechanism in multidimensional arrays - is i is a row in your example, or j... Anyway it's work just take a look at data and replace i - j - : if necessary.
Hope, it helps :)
Finally I figure out how pass from multidimensional array to each spreadsheet. I decided to arrange the data in the same multidimensional array to then pass the data to a spreadshe, using A{k}=transpose(vertcat(simulado{k,:})) and then apply a for loop to add the data to each sheet separately.
sheet = 1
for i = 1:5
xlswrite('filename.xls',A{1,i},sheet);
sheet = sheet+1;
end`

Matlab number of rows in excel file

is there a command of Matlab to get the number of the written rows in excel file?
firstly, I fill the first row. and then I want to add another rows in the excel file.
so this is my excel file:
I tried:
e = actxserver ('Excel.Application');
filename = fullfile(pwd,'example2.xlsx');
ewb = e.Workbooks.Open(filename);
esh = ewb.ActiveSheet;
sheetObj = e.Worksheets.get('Item', 'Sheet1');
num_rows = sheetObj.Range('A1').End('xlDown').Row
But num_rows = 1048576, instead of 1.
please help, thank you!
If the file is empty, or contains data in only one row, then .End('xlDown').Row; will move to the very bottom of the sheet (1048576 is the number of rows in a Excel 2007+ sheet).
Test if cell A2 is empty first, and return 0 if it is.
Or use Up from the bottom of the sheet
num_rows = sheetObj.Cells(sheetObj.Rows.Count, 1).End('xlUp').Row
Note: I'm not sure of the Matlab syntax, so this may need some adjusting
You can use MATLAB's xlsread function to read in the spreadsheet. This obtains the following fields:
[numbers strings misc] = xlsread('myfile.xlsx');
if you do a size check on strings or misc, this should give you the following:
[rows columns] = size(strings);
testing this, I got rows = 1, columns = 10 (assuming nothing else was beyond 'A' in the spreadsheet).

Resources