xlswrite different columns into excel each run

2 views (last 30 days)
smith
smith on 2 Jun 2023
Commented: Rik on 2 Jun 2023
Hello, I have this issue where, i have a matrix x that i want to write on an excel column every run, but i do not want it to overwrite itself and i do not want to specify the range every run (A1:A66/B1:B66), is there a way to make this work?
clc
close all
clear all
for i=1:55
x(i,1) = -1 + (1-(-1))*rand(1,1);
end
xlswrite ('test.xlsx', x)
Thank you!
  2 Comments
Dyuman Joshi
Dyuman Joshi on 2 Jun 2023
Define 'x' as a matrix and save the matrix.
Also, use writematrix instead of xlswrite, as xlswrite is not recommended.
smith
smith on 2 Jun 2023
clc
close all
clear all
for i=1:55
x(i,1) = -1 + (1-(-1))*rand(1,1); %% error band between (-1,1)
end
writematrix (x,'testxxx.xlsx','WriteMode','append')
Now it saves them all under the same column, I'm trying to save each run to the adjacet column, any solution?

Sign in to comment.

Answers (2)

Rik
Rik on 2 Jun 2023
If you switch to writematrix, you can set 'WriteMode' to 'append'.
If you want to stick with xlswrite, you will have to read the original contents of the file and generate the appropriate range for the data you want to write.
  2 Comments
smith
smith on 2 Jun 2023
I tried that, now it writes them all under one column, I'm trying to append them in different columns, each run in different adjacent column, any possible solution ?
Rik
Rik on 2 Jun 2023
Then you will have to use my second suggestion and generate the range based on the current contents of the file, and on what you want to write. You can use the function below.
function ExcelColName=get_ExcelColName(col_val)
%convert a col value to the Excel col name (so 27 to AA, 705 to AAC)
validateattributes(col_val,{'numeric'},{'scalar','nonzero','integer'})
base=26;
col_val=col_val-1;
digs=floor(log(col_val)/log(base))+1;%number of 'digits' (i.e. letter positions)
ExcelColName=zeros(1,digs);
for cur_d=digs:-1:1
ExcelColName(cur_d)=mod(col_val,base);
col_val=(col_val-ExcelColName(cur_d))/base;
end
if isempty(ExcelColName),ExcelColName=0;end%in case of col_val input is 1
ExcelColName(end)=ExcelColName(end)+1;
ExcelColName=char(ExcelColName+64);
end

Sign in to comment.


VBBV
VBBV on 2 Jun 2023
writematrix (x.','testxxx.xlsx','WriteMode','append')

Use the transpose for x

Products


Release

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!