Saving multiple single vectors in one Matlab file
조회 수: 4 (최근 30일)
이전 댓글 표시
Hi,
I need your help:
Here's a simple example:
A = magic(3);
B = padarray(A,[1 1]);
[row, col] = size(B);
for i = 2:row-1
for j = 2:col-1
C = [B(i-1,j-1),B(i-1,j),B(i-1,j+1),B(i,j-1),B(i,j),B(i,j+1),B(i+1,j-1),B(i+1,j),B(i+1,j+1)]
save C.mat
end
end
When you run the above code in Matlab, you will get the following output in the command window
C = 0 0 0 0 8 1 0 3 5
C = 0 0 0 8 1 6 3 5 7
C = 0 0 0 1 6 0 5 7 0
C = 0 8 1 0 3 5 0 4 9
C = 8 1 6 3 5 7 4 9 2
C = 1 6 0 5 7 0 9 2 0
C = 0 3 5 0 4 9 0 0 0
C = 3 5 7 4 9 2 0 0 0
C = 5 7 0 9 2 0 0 0 0
I would like to save the following output in C.mat file using "save" function
0 0 0 0 8 1 0 3 5
0 0 0 8 1 6 3 5 7
0 0 0 1 6 0 5 7 0
0 8 1 0 3 5 0 4 9
8 1 6 3 5 7 4 9 2
1 6 0 5 7 0 9 2 0
0 3 5 0 4 9 0 0 0
3 5 7 4 9 2 0 0 0
5 7 0 9 2 0 0 0 0
However, when I use "save" C.mat, I can only output and save one line, shown below.
5 7 0 9 2 0 0 0 0
Can you help to correct the above code to be able to save the above 9-by-9 matrix in C.mat file?
댓글 수: 0
채택된 답변
Cris LaPierre
2022년 10월 4일
You overwrite your variable C in each loop, and you overwrite C.mat as well, so the final contents are just what was created in the last loop. I would do something like the following to append the result of each loop to C rather than replace.
A = magic(3);
B = padarray(A,[1 1]);
[row, col] = size(B);
C = [];
for i = 2:row-1
for j = 2:col-1
C = [C;B(i-1,j-1),B(i-1,j),B(i-1,j+1),B(i,j-1),B(i,j),B(i,j+1),B(i+1,j-1),B(i+1,j),B(i+1,j+1)];
end
end
C
save C.mat
% Check that C.mat contains all 9 values
clear
load C.mat
C
댓글 수: 3
Cris LaPierre
2022년 10월 5일
There are multiple syntaxes you can use when calling save. Check out the documentation page to learn about each. The one you want is
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!