Cypher236
Cypher236

Reputation: 527

How to modify my MatLab script to correctly write to Excel?

So I basically have a small script in MatLab which I'm using in a much larger program. This script essentially keeps writing data to an Excel file.

The script writes data horizontally across cells and is as follows:

function writevar(x,k,filename)
    col = char(64+k);
    N = size(x,1);
    Rg = sprintf([col '1:' col '%i' ],N);
    xlswrite(filename,x,Rg)
end

The script works perfectly when writing data between columns A-Z. However it crashes once it reaches column Z. How can I modify the script so that it can keep writing beyond column Z to AA, AB, etc (it needs to go right the way down to CR).

Thanks.

Upvotes: 0

Views: 105

Answers (2)

Paamand
Paamand

Reputation: 716

One way to handle this (and see BlackAdder's comment) would be

function writevar(x,k,filename)
  if (k > 26) {
    col = [char(64+ceil(k/26)) char(64+mod(k,26))];
  else
    col = [char(64+k);
  end
  N = size(x,1);
  Rg = sprintf([col '1:' col '%i' ],N);
  xlswrite(filename,x,Rg)
end

Upvotes: 1

Mad Physicist
Mad Physicist

Reputation: 114230

You are correctly processing a values of k in the range [1, 26]. Presumably column AA would be k = 27 in your input, so you need to do some special math on that. Here is a snippet that should convert k to a column name in the general case:

k = k - 1; % Convert to zero-based for ease of processing
col = '';
while k ~= 0
    % Prepend higher digits
    col = [char(mod(k, 26) + 65) col];
    k = floor(k / 26);
end

Upvotes: 1

Related Questions