如何为GNU Octave的polyfit函数加载X、Y数据生成列向量?
加载XY坐标数据生成列向量的方法
Python 实现
原生文件操作(无需额外库)
适合小数据集,手动处理每行数据:
x_coords = [] y_coords = [] # 替换成你的数据文件路径 with open('data.txt', 'r') as file: for line in file: # 跳过空行和注释行(如果有的话) stripped_line = line.strip() if not stripped_line or stripped_line.startswith('#'): continue x, y = map(float, stripped_line.split()) x_coords.append(x) y_coords.append(y) # 输出结果 print("X坐标列向量:", x_coords) print("Y坐标列向量:", y_coords)
使用NumPy(高效处理大数据集)
如果数据量较大,用NumPy能大幅提升效率:
import numpy as np # 加载数据文件,自动处理数值分割 data_array = np.loadtxt('data.txt') # 提取第0列(X)和第1列(Y),转成列表格式 x_coords = data_array[:, 0].tolist() y_coords = data_array[:, 1].tolist() print("X坐标列向量:", x_coords) print("Y坐标列向量:", y_coords)
Matlab 实现
% 加载数据文件,文件需与脚本同目录或写全路径 data_matrix = load('data.txt'); % 提取第1列(X)和第2列(Y)的列向量 x_coords = data_matrix(:, 1); y_coords = data_matrix(:, 2); % 显示结果 disp('X坐标列向量:'); disp(x_coords); disp('Y坐标列向量:'); disp(y_coords);
内容的提问来源于stack exchange,提问作者coderodde
相关产品推荐
相关产品推荐

