How to use fprintf display values of an array that changes size.
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
t sizzle
am 22 Mär. 2021
Kommentiert: Cris LaPierre
am 22 Mär. 2021
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.
0 Kommentare
Akzeptierte Antwort
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])
2 Kommentare
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.
Weitere Antworten (1)
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
0 Kommentare
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!