# Convert matrix into CSV, with each matrix element as a separate line including indices of matrix element

조회 수: 2(최근 30일)
Daniel 2022년 9월 17일
댓글: Star Strider 2022년 9월 18일
Struggling with writematrix and having to resort to odd things like appending repeating vectors to achieve this... I am sure there must be an easier way. The size of the matrix is such that for loops etc are terribly slow.
I have a matrix like this:
0.5 0.1 0.6
0.9 0.8 0.3
I'd like to output this as a CSV in the format x, y, e - where x and y are the column and row numbers and e is the element, to give something like this:
1, 1, 0.5
2, 1, 0.1
3, 1, 0.6
1, 2, 0.9
2, 2, 0.8
3, 2, 0.3

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

### 채택된 답변

Star Strider 2022년 9월 17일
Try something like this —
M = [0.5 0.1 0.6
0.9 0.8 0.3];
[r,c] = ndgrid(1:size(M,1), 1:size(M,2));
rv = reshape(r.',[],1);
cv = reshape(c.',[],1);
Mv = reshape(M.',[],1);
A = [cv rv, Mv]
A = 6×3
1.0000 1.0000 0.5000 2.0000 1.0000 0.1000 3.0000 1.0000 0.6000 1.0000 2.0000 0.9000 2.0000 2.0000 0.8000 3.0000 2.0000 0.3000
Then use the writematrix function with a .csv suffix on the file name.
.
##### 댓글 수: 2표시숨기기 이전 댓글 수: 1
Star Strider 2022년 9월 18일
As always, my pleasure!

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

### 추가 답변(3개)

Stephen23 2022년 9월 17일
편집: Stephen23 2022년 9월 17일
M = [0.5,0.1,0.6;0.9,0.8,0.3]
M = 2×3
0.5000 0.1000 0.6000 0.9000 0.8000 0.3000
N = M.';
S = size(N);
[X,Y] = ndgrid(1:S(1),1:S(2));
writematrix([X(:),Y(:),N(:)],'test.txt')
Checking:
type test.txt
1,1,0.5 2,1,0.1 3,1,0.6 1,2,0.9 2,2,0.8 3,2,0.3
##### 댓글 수: 2표시숨기기 이전 댓글 수: 1
Stephen23 2022년 9월 17일
편집: Stephen23 2022년 9월 17일
@Dyuman Joshi: thanks, fixed now. That neatens things up too.

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

Walter Roberson 2022년 9월 17일
There are two possibilities here.
If you need every location output because in practice the data will be read as a vector of numbers and reshaped under the assumption that it is complete and in standard order, then use techniques like what Star Strider showed.
But if the individual coordinates are actively used then
[r, c, s] = find(YourMatrix);
writematrix([r, c, s], filename);
this will not write any zeros.
You would recover the matrix by reading as the columns as variables and passing them to sparse()
##### 댓글 수: 0표시숨기기 이전 댓글 수: -1

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

Dyuman Joshi 2022년 9월 17일
You can try this -
y=[0.5 0.1 0.6;0.9 0.8 0.3];
z=y';
mat=[repmat(1:size(y,2),1,size(y,1))' repelem(1:size(y,1),1,size(y,2))' z(:)]
mat = 6×3
1.0000 1.0000 0.5000 2.0000 1.0000 0.1000 3.0000 1.0000 0.6000 1.0000 2.0000 0.9000 2.0000 2.0000 0.8000 3.0000 2.0000 0.3000
And use writematrix() as Star Strider mentioned.

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

### 범주

Find more on Variables in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by