how to automatically sprintf an array elements

168 ビュー (過去 30 日間)
Homayoon
Homayoon 2017 年 5 月 21 日
コメント済み: Stephen23 2023 年 8 月 10 日
Dear All,
I have many arrays with various number of columns, that is, I have many 1*m matrices with m varies from 1 to 20. For instance, consider these three hypothetical arrays:
A1 = [1 14 20 8]
A2 = [5 1 20]
A3 = [2]
what I am after is creating a sprintf for each array to put together all array elements such that elements are separated by a dot. For the above examples, the desired outputs are
1.40.20.8 % sprintf('%d.%d.%d.%d', A1(1,1), A1(1,2), A1(1,3), A1(1,4)); three dots required
5.1.20 % sprintf('%d.%d.%d', A2(1,1), A2(1,2), A2(1,3)); two dots required
2 % sprintf('%d', A3(1,1)); no dot required
It is certainly simpler if all of the arrays have same number of columns. But since it is not the case, I have no idea how to proceed. I just want an algorithm which automatically generates the sprintf for me with the correct number of dots.
Thanks.

採用された回答

Stephen23
Stephen23 2017 年 5 月 21 日
編集済み: Stephen23 2017 年 5 月 21 日
function str = myfun(vec)
str = sprintf('.%d',vec);
str = str(2:end);
end
and tested:
>> myfun([1,14,20,8])
ans =
1.14.20.8
>> myfun([5,1,20])
ans =
5.1.20
>> myfun([2])
ans =
2
It would be great if MATLAB allowed indexing to follow a function call, as then this could be achieved in an anonymous function.
  2 件のコメント
Homayoon
Homayoon 2017 年 5 月 21 日
got it. my bad thanks
Stephen23
Stephen23 2023 年 8 月 10 日
Since R2016b using the string class:
join(string([1,14,20,8]),".")
ans = "1.14.20.8"
join(string([5,1,20]),".")
ans = "5.1.20"
join(string([2]),".")
ans = "2"

サインインしてコメントする。

その他の回答 (2 件)

amr alanwar
amr alanwar 2017 年 10 月 3 日
編集済み: amr alanwar 2017 年 10 月 3 日
For printing an array normally, you can
fprintf('\n A1 = ')
fprintf(' %.3f ', A1)
fprintf('\n A2 = ')
fprintf(' %.3f ', A2)
fprintf('\n A3 = ')
fprintf(' %.3f ', A3)
The results
A1 = 1.000 14.000 20.000 8.000
A2 = 5.000 1.000 20.000
A3 = 2.000
For your question, try playing with
fprintf('%.0f.', A1(1:end-1))
fprintf('%.0f', A1(end))
  2 件のコメント
James Tursa
James Tursa 2017 年 10 月 3 日
This does not give the desired outcome.
amr alanwar
amr alanwar 2017 年 10 月 3 日
I did not read the question carefully I modified my reply Thanks

サインインしてコメントする。


Captain Karnage
Captain Karnage 2023 年 8 月 9 日
Here's another alternative, more verbose but on a single line:
A1 = [1 14 20 8];
A2 = [5 1 20];
A3 = [2];
mystr = @(A) sprintf( [ repmat( '%d.', 1, numel(A) - 1 ), '%d' ], A );
mystr(A1)
ans = '1.14.20.8'
mystr(A2)
ans = '5.1.20'
mystr(A3)
ans = '2'

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by