MATLAB Answers

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

1 view (last 30 days)
Andi Swirbul
Andi Swirbul on 21 Nov 2020
Commented: Andi Swirbul on 22 Nov 2020
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:
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));


Stephen Cobeldick
Stephen Cobeldick on 21 Nov 2020
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 on 22 Nov 2020
Wow this is fantastic, and I especially appreciate that it didn't involve a for loop! Thank you for your wisdom.

Sign in to comment.

Accepted Answer

VBBV on 21 Nov 2020
for i = 1:length(X);

  1 Comment

Andi Swirbul
Andi Swirbul on 21 Nov 2020
Thank you so much! This worked perfectly and was exactly the type of answer I was looking for.

Sign in to comment.

More Answers (0)


Community Treasure Hunt

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

Start Hunting!