fprintf two column vectors at once
조회 수: 32 (최근 30일)
이전 댓글 표시
I have two column vectors of 1x10 and I want to find a way to fprintf or display them next to eachother like such...
vector 1:
0
-0.11
-0.22
-0.33
....
1
vector 2:
1.011
1.024
1.035
....
1.11
And I want to have them come out something like
0 1.011
-0.11 1.024
-0.22 1.035
....
1 1.11
Thank You
댓글 수: 0
채택된 답변
Voss
2022년 4월 2일
v1 = randn(10,1); % column vector, size 10-by-1
v2 = randn(10,1);
% different options:
[v1 v2]
disp([v1 v2]);
fprintf('%6.3f %6.3f\n',[v1 v2].') % pick a format you like
댓글 수: 2
Voss
2022년 4월 2일
When you send a matrix to fprintf the elements will get printed in the following order: down the first column first, then down the second column, and so on. So you have to make sure the matrix you send to fprintf has the elements in the correct order.
Constructing that matrix is different if you have row vectors vs if you have column vectors.
% Case 1: row vectors
v1 = 0:4;
v2 = 5:9;
% look at the temporary matrix that is
% constructed and sent to fprintf:
[v1; v2] % fprintf will print 0, 5, 1, 6, 2, 7, 3, 8, 4, 9
% the format says put a line-break (\n) after every two elements,
% so: 0, 5, line-break, 1, 6, line-break, etc.
fprintf('%d %d\n',[v1; v2]) % (using %d now since these are integers)
% Case 2: column vectors
v1 = (0:4).';
v2 = (5:9).';
[v1 v2].' % same matrix as above; different syntax because we have column vectors
% gives the same result as the row vector case because the matrix is
% constructed differently now
fprintf('%d %d\n',[v1 v2].')
If you don't know whether the vectors will be column vectors or row vectors, or you want to write one thing that works for both, you can do that too:
v1 = 0:4; % one row vector
v2 = (5:9).'; % one column vector
% (:) makes each vector into a column vector, for the
% purpose of constructing this matrix for fprintf
[v1(:) v2(:)].'
fprintf('%d %d\n',[v1(:) v2(:)].')
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!