MATLAB: Best practice when coding for loops

best practicefor loop

Hello everyone! When I code using for loops I always struggle between two methods of indexing. (Assume I can't do without using a for loop).
My favorite way is to use the for loop the "smart" way, by looping across an already defined vector, like:
MyVec = {'dog','cat','fish'};
for ind = MyVec
output = ComplicatedCalculations(ind);
disp(output);
end
I like this method because it is extremely flexible. Plus, it is very neat-looking code, one of the reasons I love MATLAB.
The problem is that this does not allow indexing if I also want to store the results of my calculations. So, holding a grudge, I often end up abandoning the smart way for the C-like way, which is method 2 below:
MyVec = {'dog','cat','fish'};
for ind = 1:length(MyVec)
output(ind) = ComplicatedCalculations(MyVec{ind});
disp(output(ind)); % do stuff
end
which does not look nearly as neat. So my question is: is there a way to bring together the best of both worlds, i.e. using MATLAB native smart way of for-looping, while allowing me to index the results and store them into a (possibly multi-dimensional) vector? Thanks!

Best Answer

I don't know if I agree that loop counters with non-numeric data are "smarter", but if you don't mind storing in struct form, you can do,
MyVec = {'dog','cat','fish'};
for ind = MyVec
output.(ind{1}) = ComplicatedCalculations(ind);
disp(output.(ind{1}));
end