Suggestions for a more efficient way of writing this code
2 次查看(过去 30 天)
显示 更早的评论
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
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:
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Pie Charts 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!