How to export matrix in the form of (column number, row number, value) in CSV?

2 vues (au cours des 30 derniers jours)
YYB
YYB le 18 Jan 2022
Commenté : YYB le 18 Jan 2022
I have a 100x100 matrix, and I want to export it to CSV in the form of (column number, row number, value). For example,
Matrix A:
[1] [2] [3] ... [100]
[1] 0.69 0.02 0.81 ... 0.55
[2] 0.23 0.67 0.02 ... 0.21
[3] 0.06 0.22 0.67 ... 0.96
[...] ... ... ... ... ...
[100] 0.01 0.05 0.22 ... 0.88
The expected CSV output is
Column Row Value
1 1 0.69
1 2 0.23
1 3 0.06
...
1 100 0.01
2 1 0.02
2 2 0.67
...
100 100 0.88
How can I do this in matlab? Your help is greatly appreciated.

Réponse acceptée

Voss
Voss le 18 Jan 2022
A = randn(8,4)
A = 8×4
-0.7146 -1.1106 -0.1148 -0.2202 -0.6422 0.8152 0.1026 -0.1319 0.2498 0.9995 -0.4446 -0.0136 0.8393 0.1797 0.0110 -1.1897 0.8439 -1.8116 -0.4418 0.4196 0.4376 0.5302 0.0847 -0.6413 1.1912 0.2556 -0.4474 0.3389 -1.2163 1.0390 0.7837 0.9455
[m,n] = size(A);
[c,r] = meshgrid(1:n,1:m);
writematrix([c(:) r(:) A(:)],'output.csv');
% check the result
readmatrix('output.csv')
ans = 32×3
1.0000 1.0000 -0.7146 1.0000 2.0000 -0.6422 1.0000 3.0000 0.2498 1.0000 4.0000 0.8393 1.0000 5.0000 0.8439 1.0000 6.0000 0.4376 1.0000 7.0000 1.1912 1.0000 8.0000 -1.2163 2.0000 1.0000 -1.1106 2.0000 2.0000 0.8152

Plus de réponses (0)

Catégories

En savoir plus sur Multidimensional Arrays dans Help Center et File Exchange

Tags

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by