Can I save different variables inside of a for loop?

3 ビュー (過去 30 日間)
Jaime De La Mota Sanchis
Jaime De La Mota Sanchis 2021 年 8 月 10 日
Hello everyone.
I am working with a code in which 50 variables have to be saved. Each of them is a row of a matrix. I am trying to implement this as
for i=1:50
element_of_the_ensemble=i;%de 1 a 50
windX_in_the_node=vientoX_vector(:,element_of_the_ensemble);
windY_in_the_node=vientoY_vector(:,element_of_the_ensemble);
matriz_a_enviarX_1_of_50=zeros(size(windX_in_the_node,1), 3);
matriz_a_enviarX_1_of_50(:,1:2)=positions_reducida;
matriz_a_enviarY_1_of_50=zeros(size(windY_in_the_node,1), 3);
matriz_a_enviarY_1_of_50(:,1:2)=positions_reducida;
matriz_a_enviarX_1_of_50(:,3)=windX_in_the_node;
matriz_a_enviarY_1_of_50(:,3)=windY_in_the_node;
save('Xdata_'+i+'_of_50', 'matriz_a_enviarX_1_of_50')
save('Ydata_'+i+'_of_50', 'matriz_a_enviarY_1_of_50')
end
I have based this attempt in this other question. Unfortunately, I obtain an error.
Error using save
Must be a text scalar.
Error in read_data (line 619)
save('Xdata_'+i+'_of_50', 'matriz_a_enviarX_1_of_50')
So, it seems that my idea doesn't work.
Can someone please tell me if I can really automate this process?
Best regards.
Jaime.

採用された回答

Scott MacKenzie
Scott MacKenzie 2021 年 8 月 10 日
編集済み: Scott MacKenzie 2021 年 8 月 10 日
Create the desired name of the file as a string or character variable, then use that variable with the save command. For example,
filename = sprintf('Xdata_%d_of_50', i);
save(filename, 'matriz_a_enviarX_1_of_50')
  1 件のコメント
Jaime De La Mota Sanchis
Jaime De La Mota Sanchis 2021 年 8 月 10 日
Thank you very much. This does it perfectly

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

その他の回答 (1 件)

Andreas Mittnacht
Andreas Mittnacht 2021 年 8 月 10 日
Hi Jaime,
  1. for better performance do calculation without a loop
  2. to save data, use
save('Xdata_%d_of_50', i 'matriz_a_enviarX_1_of_50')
  1 件のコメント
Jaime De La Mota Sanchis
Jaime De La Mota Sanchis 2021 年 8 月 10 日
Thanks for the answer. However, if I implement it I obtain the following error:
Error using save
Must be a text scalar.
Error in read_data (line 619)
save('Xdata_%d_of_50', i, 'matriz_a_enviarX_1_of_50')
I have tested if I need another comma after the i, but the error persists.

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by