【问题标题】:Using xlswrite to save data from an array? Matlab使用 xlswrite 保存数组中的数据? MATLAB
【发布时间】:2014-06-23 19:49:05
【问题描述】:

我用 matlab 创建了一个 GUI,最后用户可以选择保存数据并将其保存到他们选择的 excel 文件中。
有两组单独的数据保存并写入 excel 文件。第一个是一个数值IntensityValue2,例如4592.25OtherAUC2,这是一个不同数值的数组,例如[] [5025.8] [5012.3] [4963.45]
这是我正在使用的代码:

% --- Executes on button press in Save.
function Save_Callback(hObject, eventdata, handles)
% hObject    handle to Save (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
IntensityValue = getappdata(0,'IV');

[FileName,PathName]= uigetfile('*.xlsx*','File to save to');
intensityfile = fullfile(PathName,FileName);
filename = intensityfile;
mypeak = {'Peak(nm)'};
xlswrite(filename,mypeak,'Sheet1','A1');
myintensity = {'Intensity'};
  xlswrite(filename,myintensity,'Sheet1','B1');
IntensityValue2 = str2num(IntensityValue);
  xlswrite(filename,IntensityValue2,'Sheet1','B2');
OtherAUC = getappdata(0,'AUC')
numfiles = getappdata(0,'files');
for a = 2:numfiles
    OtherAUC2{a} = OtherAUC{a}
end
xlswrite(filename,OtherAUC2,'Sheet1','B3');  

目前excel文件看起来像这样:

Peak(nm)  Intensity
          4592.25  
                    5025.8  5012.3  4963.45  

而我希望它看起来像这样:

Peak(nm)   Intensity  
           4592.25
           5025.8  
           5012.3  
           4963.45  

谁能帮我实现这个目标?我意识到OtherAUC2 中的第一个单元格是空的,但我认为 foror 循环意味着第一个单元格没有写入 excel 文件。任何帮助或建议将不胜感激!

【问题讨论】:

  • 对于方向,转置 OtherAUC2 应该可以解决问题 (OtherAUC2.')。指定确切的单元格范围也应该有效,但不够灵活。对于空白单元格,whosOtherAUCOtherAUC2 的结果是什么?
  • @excaza 谢谢我会尝试转置OtherAUC2。其他AUC 的whos 的结果是Name: OtherAUC Size: 1x4 Bytes:368 Class:cell Attributes:,OtherAUC2 的结果是Name: OtherAUC2 Size: 1x4 Bytes:368 Class:cell Attributes:
  • 哦,呃,我第一次看时错过了。使用OtherAUC2{a-1} = OtherAUC{a}
  • @excaza 非常感谢!

标签: matlab user-interface xls


【解决方案1】:

回顾一下:

xlswrite 将数据写入 excel 文件时,布局将与 MATLAB 中的布局相同。因此,如果您有一个 1x4 数组,它将写入一行,如果您有一个 4x1 数组,它将写入一列。要重塑此数组,您可以使用 MATLAB 的 transpose 函数,该函数通常缩写为 .'(复共轭)或 '(转置)。在这种情况下,所有三个都是等价的。

所以对于您的应用程序,您有两种方法:

OtherAUC2 = OtherAUC2.';
xlswrite(filename,OtherAUC2,'Sheet1','B3');

% or

xlswrite(filename,OtherAUC2.','Sheet1','B3');

这两种方法都应该为您提供所需的结果。

对于第二部分,您的 for 循环只需要调整即可。您正确地从 2 开始循环索引以跳过空白值,但您忘记考虑新数组中的索引移位。

您需要做的就是从您的OtherAUC2 索引中减去一个:

for a = 2:numfiles
    OtherAUC2{a-1} = OtherAUC{a}
end

或者,您可以在没有循环的情况下删除空单元格:

OtherAUC = OtherAUC(~cellfun(@isempty, OtherAUC));

cellfun 将指定的函数应用于元胞数组中的每个元胞,这在许多情况下消除了循环的需要。这里它正在做的是遍历每个单元格并查看它是否为空。然后它将OtherAUC 重新定义为每个不为空的单元格。这是logical indexing 的示例(~cellfun(@isempty, OtherAUC) 返回一个 1x4 逻辑数组,其中FALSE 是一个空单元格)。

你可以用一个数值数组来完成同样的事情:

test = [NaN,2,3,4];
test(isnan(test)) = [];

% or

test = [0,2,3,4];
test(test==0) = []; 

在比较非整数而不使用容差时,请注意floating point errors

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多