Saving multiple single vectors in one Matlab file
3 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Cris LaPierre
on 4 Oct 2022
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 Comments
Cris LaPierre
on 5 Oct 2022
There are multiple syntaxes you can use when calling save. Check out the documentation page to learn about each. The one you want is
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!