How to use fprintf display values of an array that changes size.
조회 수: 7 (최근 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!