Saving multiple single vectors in one Matlab file
1 次查看(过去 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!