user288609
user288609

Reputation: 13025

regarding saving the numerical and string values altogether

I have a string matrix with N rows and 2 columns. Each cell stores a string. I have another N*1 vector, where each entry is a numerical value.

How can I save these two structures into a single text file row by row.

In other words, each row of the saved text file is composed of three elements, the first two elements come from a row of the string matrix and the third element comes from the corresponding row of that vector.

Thanks.

Upvotes: 0

Views: 31

Answers (1)

St-Ste-Ste-Stephen
St-Ste-Ste-Stephen

Reputation: 1076

If I understand correctly, then fake data can be represented as this:

% Both have N=2 rows
strMat1 = {'a','b';'c','d';};
strMat2 = {1;2};

And if you want the output of this data to be a text file with:

ac1
bd2

Then you should do this:

txtOut = [];
if size(strMat1,1) == size(strMat2,1);
    for row = 1:size(strMat1,1)
        txtOut= [txtOut strMat1{:,row} num2str(strMat2{row}) '\n'];
    end
else
    disp('Size disagreement')
end

fid=fopen('textData.txt','wt');
fprintf(fid,txtOut)

It checks the vectors to make sure there are the same number of rows and then creates a txtOut string to be passed to a fprintf command.

Hope this helps! If you wanted the output to be spaced differently, just add spaces to the appending line in the form of ' ' .

Upvotes: 1

Related Questions