How to use fprintf display values of an array that changes size.
10 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Cris LaPierre
2021-3-22
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 个评论
Cris LaPierre
2021-3-22
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.
更多回答(1 个)
Image Analyst
2021-3-22
Try it this way
for k = 1 : length(A)
fprintf('Generic message at %g is %g.\n', A(k), Z(k));
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!