MATLAB Answers

Overwrite single row excel information based on Unique ID in column data

조회 수: 2(최근 30일)
Ganesh Naik
Ganesh Naik 2021년 6월 1일
답변: Vimal Rathod 2021년 6월 7일
Hi all,
Each time when I execute some functions I am storing the results in an excel file. Rows of column one contains unique ID for each subject. Whenever I execute the function new results are automatically appended into a new row. Whenever the same information is executed, I would like to overwrite rows containing unique ID information with a warning sign such as “The information is already exists would you like to overwrite them” etc. I tried this with “unique” function in matlab but no success. Any help in this regard is highly appreciated.
  댓글 수: 2
Ganesh Naik
Ganesh Naik 2021년 6월 2일
Hi Monika, thanks for your email. Please find below the code and excel sheet attached. I would like to overwrite any rows if the data with same lastname is executed. I have created a dummy problem to reflect my original data.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
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'));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

댓글을 달려면 로그인하십시오.

답변(1개)

Vimal Rathod
Vimal Rathod 2021년 6월 7일
Hi,
You could use the find and strcmp functions to find the index where the name or uniqueIndex matches.
newName = "Diana";
data = readtable('BP_Analysis.xlsx','PreserveVariableName', true);
idx = find(strcmp(data.Lastname,newName));
If find function returns empty column vector then there is no match in the available uniqueIds and you could append or else if idx is a number you will get the index.
Refer the following links to know more about find and strcmp functions.

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by