【问题标题】:Overwrite single row excel information based on Unique ID in column data根据列数据中的唯一ID覆盖单行excel信息
【发布时间】:2021-06-03 15:04:20
【问题描述】:

每次执行某些函数时,我都会将结果存储在 Excel 文件中。第一列的行包含每个主题的唯一 ID。每当我执行该函数时,新结果都会自动附加到新行中。每当执行相同的信息时,我想用警告标志覆盖包含唯一 ID 信息的行,例如“信息已经存在,你想覆盖它们吗”等。我在 matlab 中使用“唯一”函数尝试了这个,但没有成功。非常感谢这方面的任何帮助。

到目前为止我的代码如下:

LastName = {'Sam';'John';'Bella';'Diana';'Kelly'};
Age = [48;53;58;80;29];
Smoker = logical([1;0;1;0;1]);
Height = [61;59;64;69;62];
Weight = [126;153;141;153;129];
BloodPressure = [104 95; 119 79; 115 85; 127 85; 112 81];
Table = table(LastName,Age,Smoker,Height,Weight,BloodPressure)
writetable(Table,"BP_Analysis.xlsx","WriteMode","append","AutoFitWidth",false);

%Overwirte the rows "Lastname" if same results are executed again. 
data = readtable('BP_Analysis.xlsx','PreserveVariableName', true);
data.Properties.VariableNames{1} = 'Lastname';
[~,idx]=unique(strcat('Lastname','rows'));

如果再次执行具有相同姓氏的数据,我想覆盖任何行中的所有信息。我创建了一个虚拟问题来反映我的原始数据。

【问题讨论】:

    标签: excel matlab


    【解决方案1】:

    使用上面 sn-p 中的 xlsx 文件,您可以这样做:

    如果新行中的 LastName 是“Sam”,那么:

    newLastName = 'Sam';
    idx = contains(data.LastName, newLastName)
    

    现在,idx 将包含与“Sam”匹配的所有现有条目的行索引,因此您可以对它们进行索引以覆盖、添加警告等。

    if any(idx)
        % throw warning, ...
    end
    
    for j = 1:numel(idx)
        if idx(j) == 1
            % replace the row:
            data(j, :) = % ...
        end
    end
    

    【讨论】:

    • 您可以使用for j = find(idx(:).') 循环遍历idx 为真的索引,并删除嵌套的if 条件。
    • 嗨,“akamath”和“Wolfe”感谢您的回答和帮助。我将根据您的建议更新我的代码。亲切的问候
    猜你喜欢
    • 2022-09-23
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 2011-12-24
    • 2020-04-15
    • 1970-01-01
    相关资源
    最近更新 更多