How to Export and append in a csv file?

조회 수: 2 (최근 30일)
MICHELE
MICHELE 2015년 3월 3일
댓글: Walter Roberson 2024년 11월 22일
Hi everyone,
I have a scrip where I have few list which I use to control some input and do some calculation. At the end of the process I have always something like
Vector_1={'Solar in', 0, 0, 0, 10; 'Solar Out',0,0,0,0,5}; Vector_2={'Boiler in', 0, 0, 0, 10; 'Boiler Out',0,0,0,0,5};
After obtain the two lists I create a new list by combine the previous ones. Input=[Vector_1;Vector_2];
Then I want to export and append at each step Input in a csv file doing this:
dlmwrite('Input.csv', Input,'-append')
but I got this error :
Error using dlmwrite (line 118) The input cell array cannot be converted to a matrix.
Thanks for any advice!

답변 (1개)

Rajanya
Rajanya 2024년 11월 22일
I’ve been able to reproduce the issue on my end and it seems the error you are facing stems from the fact that ‘dlmwrite’ only takes a cell array of numeric values as an input argument; but ‘Input’ has mixed type data.
As a workaround, you could convert ‘Input’ to a table and then use ‘writetable’ in append mode to achieve the same result.
For example, the code could look like:
Vector_1={'Solar in', 0, 0, 0, 10; 'Solar Out',0,0,0,5}; %this had one 0 extra
Vector_2={'Boiler in', 0, 0, 0, 10; 'Boiler Out',0,0,0,5}; %same here
Input=[Vector_1;Vector_2];
T=cell2table(Input); %convert to a table
writetable(T, 'Input_.csv', 'WriteVariableNames', false, 'WriteMode', 'append');
writetable(T, 'Input_.csv', 'WriteVariableNames', false, 'WriteMode', 'append');
This successfully appends ‘T’ at the end of ‘Input_.csv’ file as shown:
If ‘WriteMode’ is not supported for ‘writetable’ in your version of MATLAB, you can append the data manually to the file, following something like this:
if exist('Input_.csv', 'file')
T_existing = readtable('Input_.csv', 'ReadVariableNames', true); %take care of the variable names
% as they should match for proper appending
T_new = [T_existing; T]; % Concatenate the existing and the new data (stored in T)
else
T_new = T; %just the new data (stored in T)
end
writetable(T_new, 'Input_.csv', 'WriteVariableNames', true);
For more information on ‘dlmwrite’ or ‘writetable’, you can visit their respective documentation pages by executing the following commands from the MATLAB Command Window:
doc dlmwrite
doc writetable
Thanks!
  댓글 수: 1
Walter Roberson
Walter Roberson 2024년 11월 22일
It would be more natural to use writecell -- other than the fact that writecell was introduced in R2019a and this question was asked in 2015 time-frame.

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

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by