Suggestions for a more efficient way of writing this code

2 ビュー (過去 30 日間)
Grey
Grey 2017 年 11 月 20 日
コメント済み: DGM 2024 年 9 月 24 日
Basically I have to do the same process a number of times, looping through different variables, and secondary variables.
In total, I have 9 variables: {'y' 'pi' 'r' 'i' 'v' 'a' 'z' 'ye' 'pie'} And I have to repeat the process 3 times within each variable.
This is what I have so far:
resp1y(:,1)=squeeze(resp(1,1,:));
resp2y(:,1)=squeeze(resp(1,2,:));
resp3y(:,1)=squeeze(resp(1,3,:));
resp1pi(:,1)=squeeze(resp(2,1,:));
resp2pi(:,1)=squeeze(resp(2,2,:));
resp3pi(:,1)=squeeze(resp(2,3,:));
resp1r(:,1)=squeeze(resp(3,1,:));
resp2r(:,1)=squeeze(resp(3,2,:));
resp3r(:,1)=squeeze(resp(3,3,:));
resp1i(:,1)=squeeze(resp(4,1,:));
resp2i(:,1)=squeeze(resp(4,2,:));
resp3i(:,1)=squeeze(resp(4,3,:));
resp1v(:,1)=squeeze(resp(5,1,:));
resp2v(:,1)=squeeze(resp(5,2,:));
resp3v(:,1)=squeeze(resp(5,3,:));
resp1a(:,1)=squeeze(resp(6,1,:));
resp2a(:,1)=squeeze(resp(6,2,:));
resp3a(:,1)=squeeze(resp(6,3,:));
resp1z(:,1)=squeeze(resp(7,1,:));
resp2z(:,1)=squeeze(resp(7,2,:));
resp3z(:,1)=squeeze(resp(7,3,:));
resp1ye(:,1)=squeeze(resp(8,1,:));
resp2ye(:,1)=squeeze(resp(8,2,:));
resp3ye(:,1)=squeeze(resp(8,3,:));
resp1pie(:,1)=squeeze(resp(9,1,:));
resp2pie(:,1)=squeeze(resp(9,2,:));
resp3pie(:,1)=squeeze(resp(9,3,:));
As you can see, there is a lot of repetition. My initial idea what so dynamically rename the vectors (but I read that it is not recommended -- also, I couldn't make it work). I tried something like this:
j = 0
for vars = {'y' 'pi' 'r' 'i' 'v' 'a' 'z' 'ye' 'pie'}
j = j + 1
for i = 1:3
resp{i}{vars}(:,1)=squeeze(resp(j,i,:))
end
end
Any suggestions on how to get the same output that I have right now, but in a considerable lower amount of lines?
Thanks!

回答 (1 件)

Gautam
Gautam 2024 年 9 月 24 日
Hello Grey,
Assuming that you want to maintain the variable names as you have specified, since you are retrieving the data from a matrix and there are no mathematical operations involved, dynamically naming the variables cannot be helped.
However, you can use structures to better organize your data
variables = {'y', 'pi', 'r', 'i', 'v', 'a', 'z', 'ye', 'pie'};
respStruct = struct();
for j = 1:length(variables)
for i = 1:3
fieldName = sprintf('resp%d%s', i, variables{j});
respStruct.(fieldName)(:,1) = squeeze(resp(j,i,:));
end
end
The structure respStruct uses dynamic field names based on the elements in variables. Instead of creating variables like resp1y, resp2y, etc., you store them in a structured manner, which is more manageable and less error-prone.
You can refer to the following documentation on structures in MATLAB for more information:

カテゴリ

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

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by