0

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.

3
  • Your problem is the line char(64+k). Once you reach the ASCII code for Z (90) you will get the ASCII code of [ (91). You need to handle this case adding a second char on the left and reset the first one to 64 (ASCII for 'A'). This way you will get without problems up to ZZ. Commented Jul 5, 2016 at 13:09
  • @BlackAdder Aah I see, thank you! Commented Jul 5, 2016 at 13:47
  • Possible duplicate of Convert Excel Column Number to Column Name in Matlab Commented Jul 5, 2016 at 15:36

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

3 Comments

This solutions only goes to column 'ZZ'. Otherwise see Mad Physicist's answer.
Thank you for your answer! It's still helpful to see how it's done appreciate it!
I strongly suspect that your code won't work. Last time I checked, curly braces are only used for cell arrays in MATLAB.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.