How to use fprintf to show collated values for two arrays.

25 次查看(过去 30 天)
I have filtered a large amount of data and found X and Y values that I need to print:
X = [189;189;189;190;190;190;191;191;191]
Y = [299;300;301;299;300;301;299;300;301]
To clarify, I need to print the first value of X with the first value of Y, then the second value of X with the second value of Y, and so on and so forth.
I currently have the following code:
fprintf("(%d,%d) \n", X, Y);
However, this is the output that I am given:
(189,189)
(189,190)
(190,190)
(191,191)
(191,299)
(300,301)
(299,300)
(301,299)
(300,301)
As you can see, all nine values of X are printed first, then all nine values of Y.
I know I could use the following, but I was hoping there is a more efficient sollution.
fprintf("(%d,%d) \n", X(1), Y(1));
fprintf("(%d,%d) \n", X(2), Y(2));
fprintf("(%d,%d) \n", X(3), Y(3));
fprintf("(%d,%d) \n", X(4), Y(4));
fprintf("(%d,%d) \n", X(5), Y(5));
fprintf("(%d,%d) \n", X(6), Y(6));
fprintf("(%d,%d) \n", X(7), Y(7));
fprintf("(%d,%d) \n", X(8), Y(8));
fprintf("(%d,%d) \n", X(9), Y(9));
  2 个评论
Stephen23
Stephen23 2020-11-21
More efficient than using a loop:
X = [189;189;189;190;190;190;191;191;191];
Y = [299;300;301;299;300;301;299;300;301];
fprintf("(%d,%d) \n",[X,Y].')
(189,299) (189,300) (189,301) (190,299) (190,300) (190,301) (191,299) (191,300) (191,301)
Andi Swirbul
Andi Swirbul 2020-11-22
Wow this is fantastic, and I especially appreciate that it didn't involve a for loop! Thank you for your wisdom.

请先登录,再进行评论。

采纳的回答

VBBV
VBBV 2020-11-21
for i = 1:length(X);
fprintf('%d,%d\n',X(i),Y(i));
end

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Introduction to Installation and Licensing 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by