如何在Octave/Matlab中无需指定列数加载文本为字符串二维数组?
Hey there! I get exactly what you're trying to do here—load that text file with its original line and column structure into a 2D string array in Octave/Matlab, without having to hardcode the number of columns beforehand. Let's jump straight to the built-in solutions that fit your "no reinventing the wheel" requirement.
Method 1: Modern Octave (5.0+) – Using readlines (Recommended)
Octave 5.0 and later have the readlines function that makes this super straightforward. It reads each line of the file as a separate string, which we can then split into columns:
% Step 1: Read all lines from the file all_lines = readlines('test.dat'); % Step 2: Split each line into space-separated elements, then combine into 2D array split_lines = cellfun(@(line) split(line, ' '), all_lines, 'UniformOutput', false); data = vertcat(split_lines{:});
Running this will give you a 2×3 string array (or cell array, depending on your Octave version) that perfectly matches the original file's structure:
- Row 1:
foo,bar,baz - Row 2:
qux,ham,spam
Method 2: Compatible with Older Octave Versions
If you're stuck on an older Octave release without readlines, you can use fileread + strsplit to achieve the same result:
% Step 1: Read the entire file as a single string file_content = fileread('test.dat'); % Step 2: Split the content into individual lines (remove empty lines if needed) all_lines = strsplit(file_content, '\n'); all_lines = all_lines(~cellfun(@isempty, all_lines)); % Step 3: Split each line into columns and assemble the 2D array split_lines = cellfun(@(line) strsplit(line, ' '), all_lines, 'UniformOutput', false); data = vertcat(split_lines{:});
Why Your Original textscan Approach Didn't Work
The issue with your initial code is that by default, textscan treats all whitespace (spaces, newlines, tabs, etc.) as delimiters. That's why it dumped every single word into a 1D array instead of respecting the line breaks. The parameters you tried adjusting didn't fix this because you weren't telling it to process lines as individual rows first.
Both methods above avoid this by first preserving the line structure, then splitting each line into columns—no need to predefine how many columns there are!
内容的提问来源于stack exchange,提问作者Wrzlprmft

