Filter löschen
Filter löschen

How to use fprintf display values of an array that changes size.

7 Ansichten (letzte 30 Tage)
I am trying to use fprintf to display a message along the lines of 'generic message at A is Z'. Arrays A and Z consist of every other value from an array. So far I have tried this.
A = array1(1:2:end)
Z = array2(1:2:end)
%creates an array of everyother value from an original array
fprintf('\n generic message at %g is %g \n', A, Z)
However, this does not result in the desired message I am looking for. I would like it to print out something like
"generic message at 1 is 2"
"generic message at 2 is 6"
and so on until there are no more values left in arrays A and Z.

Akzeptierte Antwort

Cris LaPierre
Cris LaPierre am 22 Mär. 2021
Consider combining your two vectors into an array. Since MATLAB uses column-major ordering by default, it will use the numbers from the first column, top to bottom, then the 2nd column, etc. This means you should put the values for A in the first row, and the values for Z in the second. This method assumes A and Z are the same length.
See this example.
array1 = 1:5;
array2 = 7:11;
A = array1(1:2:end);
Z = array2(1:2:end);
%creates an array of every other value from an original array
fprintf('\n generic message at %g is %g \n', [A; Z])
generic message at 1 is 7 generic message at 3 is 9 generic message at 5 is 11
  2 Kommentare
t sizzle
t sizzle am 22 Mär. 2021
Thank you. I had two horizontal arrays (or vectors, I'm honestly not sure the exact difference between the two). I made a new array that consisted of both previous ones turned vertically in their own column. This worked for me.
Cris LaPierre
Cris LaPierre am 22 Mär. 2021
When the number of format specs is not equal to the number of values, MATLAB will use all the numbers in the first variable before moving to the second variable.
You can take advantage of how numbers are stored in memory to obtain the desired behavior. This is where the column major refrence is applicable. By combining the two vectors into an array where A is in the first row and Z is in the second, the numbers are stored in memory starting with the first value of A, followed by the first value of Z, followed by the second value of A, etc.
When creating your string, MATLAB pulls in the numbers based on how they are stored in memory.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Image Analyst
Image Analyst am 22 Mär. 2021
Try it this way
for k = 1 : length(A)
fprintf('Generic message at %g is %g.\n', A(k), Z(k));
end

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by