How can i make array with strings ?

9 ビュー (過去 30 日間)
Akshay Kumar
Akshay Kumar 2020 年 2 月 6 日
回答済み: Guillaume 2020 年 2 月 6 日
I need to make a array with strings. For exmaple I have tried this.
for i =1:100
for j =1:200
D(i,j) = sprintf('z_prop(%d,%d,hbsigmci)=%.4f;',i,j,normrnd(0,1));
end
end
I am getting error in assignment. Provide solution to error or Alternate way.
Thaks.
  2 件のコメント
Rik
Rik 2020 年 2 月 6 日
What do you want to with this? It looks like you are preparing something with eval, which I would strongly discourage.
Also, do you want the result to be of the string class or the char class?
Stephen23
Stephen23 2020 年 2 月 6 日
編集済み: Stephen23 2020 年 2 月 6 日
This looks like the start of some slow, complex, obfscuated, buggy code:
'z_prop(%d,%d,hbsigmci)=%.4f;'
What are you planning on doing with that character vector? Why not just assign that value directly?:
z_prop(i,j,hbsigmci) = normrnd(0,1);

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

採用された回答

Guillaume
Guillaume 2020 年 2 月 6 日
Note that strictly speaking you're not creating strings but char vectors. You may actually prefer generating strings which are easier to work with. If you want string simply replace the single quotes ' by double quotes " and you'll find that your code work exactly as you expected. However, you should preallocate the output array before the loop for efficiency:
D = strings(100, 200); %preallocate array
for j = 1:200
for i = 1:100
D(i, j) = sprintf("z_prop(%d,%d,hbsigmci)=%.4f;",i,j,normrnd(0,1));
end
end
If you want to work with char vectors, you need to store them in a cell array, not a matrix:
D = cell(100, 200);
for j = 1:200
for i = 1:100
D{i, j} = sprintf('z_prop(%d,%d,hbsigmci)=%.4f;',i,j,normrnd(0,1));
end
end
Note: another way to generate your output, which doesn't involve a loop
[r, c] = ndgrid(1:100, 1:200);
hbsigmci = normrnd(0, 1, size(r));
%for strings:
Dstring = reshape(compose("z_prop(%d,%d,hbsigmci)=%.4f;", r(:), c(:), hbsigmci(:)), size(r));
%for char vectors
Dchar = reshape(compose('z_prop(%d,%d,hbsigmci)=%.4f;', r(:), c(:), hbsigmci(:)), size(r));

その他の回答 (1 件)

Bhaskar R
Bhaskar R 2020 年 2 月 6 日
編集済み: Bhaskar R 2020 年 2 月 6 日
In string related operations use cell array data type as
D = cell(100, 200);
for i =1:100
for j =1:200
D{i, j} = sprintf('z_prop(%d,%d,hbsigmci)=%.4f;',i,j,normrnd(0,1));
end
end

カテゴリ

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