フィルターのクリア

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

7 ビュー (過去 30 日間)
t sizzle
t sizzle 2021 年 3 月 22 日
コメント済み: Cris LaPierre 2021 年 3 月 22 日
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.

採用された回答

Cris LaPierre
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])
generic message at 1 is 7 generic message at 3 is 9 generic message at 5 is 11
  2 件のコメント
t sizzle
t sizzle 2021 年 3 月 22 日
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 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
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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by