You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在循环中向元胞数组添加不同长度列并为其设置标签

Got it, let's break down how to solve this problem. You're working in MATLAB, extracting data from CSV files in a loop, and need to build a cell array that can hold columns of different lengths—plus assign clear labels to each of those columns. Here's how to integrate this into your existing code, with explanations every step of the way:

Solution: Build a Variable-Length Column Cell Array with Labels in MATLAB

First, let's extend your existing startup code to include the logic for loading CSV files, populating the cell array, and tracking column labels. This example assumes you're processing paired strain/stress files, but you can adjust the loop logic to fit your exact file structure:

% Startup
clearvars;
path = pwd; % Set default path to your current working directory (tweak if needed)
stress_folder = uigetdir(path,'Select STRESS folder');
strain_folder = uigetdir(path,'Select STRAIN folder');

prompt = {'Plot name:','x label (strain):','y label (stress):','Name of STRAIN values:','Name of STRESS values:'};
dlg_title = 'Input';
num_lines = 1;
defaultans = {'Title','x label','y label','Surface component 1.avg(epsY) [True strain]','Stress'};
answer = inputdlg(prompt,dlg_title,num_lines,defaultans);

% Pull out user inputs for easy reference
plot_title = answer{1};
x_label = answer{2};
y_label = answer{3};
strain_base_label = answer{4};
stress_base_label = answer{5};

% --------------------------
% Initialize storage structures
% --------------------------
% Cell array to hold variable-length columns (each cell = one column of data)
data_cell = {};
% Matching cell array to store labels for each column
col_labels = {};

% --------------------------
% Loop through your CSV files
% --------------------------
% Get list of all CSV files in each folder
strain_files = dir(fullfile(strain_folder, '*.csv'));
stress_files = dir(fullfile(stress_folder, '*.csv'));

% Loop through each pair of strain/stress files (adjust if you're processing single files)
for i = 1:length(strain_files)
    % Load strain data from CSV (use readtable instead if your CSVs have headers)
    strain_file_path = fullfile(strain_folder, strain_files(i).name);
    strain_data = readmatrix(strain_file_path);
    
    % Load stress data from CSV
    stress_file_path = fullfile(stress_folder, stress_files(i).name);
    stress_data = readmatrix(stress_file_path);
    
    % --------------------------
    % Add data + labels to your cell arrays
    % --------------------------
    % Add strain column and a unique label (include filename for clarity)
    data_cell{end+1} = strain_data;
    col_labels{end+1} = [strain_base_label ' - ' strain_files(i).name];
    
    % Add stress column and its unique label
    data_cell{end+1} = stress_data;
    col_labels{end+1} = [stress_base_label ' - ' stress_files(i).name];
end

% --------------------------
% Example: Check your results
% --------------------------
disp('Here are your column labels:');
celldisp(col_labels);

disp('Preview of each data column (first 5 elements):');
for j = 1:length(data_cell)
    fprintf('Column %d (%s):\n', j, col_labels{j});
    % Show first 5 elements, or the full column if it's shorter than 5 rows
    disp(data_cell{j}(1:min(5, length(data_cell{j}))));
end

% --------------------------
% Example: Plot a pair of columns (first strain + first stress)
% --------------------------
figure;
plot(data_cell{1}, data_cell{2}, 'LineWidth', 1.5);
title(plot_title);
xlabel(x_label);
ylabel(y_label);
grid on;

Key Details to Note:

  • Variable-Length Support: MATLAB cell arrays are perfect for this job—each cell can hold an array of any length, so you don't have to worry about mismatched row counts between CSV files.
  • Label Sync: The col_labels array mirrors data_cell exactly. Every index in col_labels corresponds to the column at the same index in data_cell, so you'll always know what each column contains.
  • CSV Loading Flexibility: I used readmatrix for simplicity, but if your CSVs have headers, swap it out for readtable and extract the specific column you need (e.g., strain_data = table2array(strain_table(:, 'StrainColumn'));).
  • Loop Customization: If you're not processing paired files, adjust the loop to load individual CSVs and assign labels based on your file naming convention or user input.

Quick Troubleshooting:

  • If some CSV files have wonky formatting, add a try/catch block inside the loop to skip problematic files and log errors.
  • To filter or sort columns later, use the col_labels array to target specific data (e.g., stress_col_indices = contains(col_labels, 'Stress'); stress_columns = data_cell(stress_col_indices);).

内容的提问来源于stack exchange,提问作者enea19

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:55:33