About creating a string of specified length

15 ビュー (過去 30 日間)
Heng
Heng 2014 年 7 月 6 日
コメント済み: Image Analyst 2014 年 7 月 6 日
The goal is to create a string of specified length with the same chars. For example, given variable n=5, I want to obtain 'AAAAA'. at first I used the following code:
s(1:n)='A';
But I was not sure if it is correct because I don't know how matlab decides the end of the string. We all know that in C any string is ended with '\0', but what about matlab? Also, if s is first assigned a long string, and then a shorter one, like this:
s(1:5)='A';
s(1:3)='B';
s would be BBBAA, instead of BBB as expected. So I then rewrite the code as follows:
s='';
s(1:n)='A';
Is the above code absolutely correct? If not, should the following code a standard (and correct) way of creating a string of specified length n with the same char?
s=blanks(n);
s(1:n)='A';
Thanks for any help.

採用された回答

Image Analyst
Image Analyst 2014 年 7 月 6 日
Your code is fine. You do not need to initialize s to '' though - that doesn't do anything once all is said and done. For the BBBAA case, the first line makes 5 A's. The second line assigns the first three elements of it to B and leaves elements 4 and 5 as A, as I (though not you) expected. If you wanted just BBB you wouldn't use the 1:3 index. That is equivalent to
for k = 1 : 3
s(k) = 'B'
end
If you want BBB, just leave out the indexes and write s = 'BBB'. In that case there will be no trailing A's. I hope that explains it better.
  2 件のコメント
Heng
Heng 2014 年 7 月 6 日
Thank you but n is a variable, we don't know the exact value of n so we can't simply write 'BBB'. my question is: is s(1:n)='A' safe, i.e., does matlab really know the string is of length n and this assignment would never cause any memory access fault?
Image Analyst
Image Analyst 2014 年 7 月 6 日
Use repmat() to replicate a matrix (or even a single number of character):
s = repmat('A', [1, n]) % Replicate 1 time vertically, n times horizontally.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by