I want to extract data from a for loop a created instead of individually coding each vaiable, is there an easier way in MATLAB 2015b?

1 view (last 30 days)
for n=(1:14)
load(['lok' num2str(n) '.mat'])
load(['lokf' num2str(n) '.mat'])
end
F1 =lok1dat(1:600,1)
F2 =lok2dat(1:600,1)
F3 =lok3dat(1:600,1)
F4 =lok4dat(1:600,1)
F5 =lok5dat(1:600,1)
F6 =lok6dat(1:600,1)
F7 =lok7dat(1:600,1)
F8 =lok8dat(1:600,1)
F9 =lok9dat(1:600,1)
F10=lok10dat(1:600,1)
F11=lok11dat(1:600,1)
F12=lok12dat(1:600,1)
F13=lok13dat(1:600,1)
F14=lok14dat(1:600,1)
  3 Comments
Star Strider
Star Strider on 8 Nov 2015
We do not know all the details. Apparently the .mat files were created separately. We don’t know anything about them except that one variable in them are the data he wants to work with.
Peter wants help to make his code run as efficiently as possible, not a lecture. I provide an efficient solution...
Stephen23
Stephen23 on 8 Nov 2015
Edited: Stephen23 on 19 Jun 2019
eval is certainly not an efficient solution in terms of program running time, where it is considerably slower than simply calling functions directly.
eval is much less efficient in terms of wasted time debugging eval strings, because none of the inbuilt code checking and code hinting work with eval. Beginners who choose to use eval effectively disable all of MATLAB's code help tools. Removing all of MATLAB's inbuilt tools that help to write and understand code (e.g. variable highlighting, which does not work with evaluated variables, or function hinting or f1 help menu, syntax highlighting, etc) does not make writing code more efficient, it makes it harder.
eval has a much less efficient use of memory because MATLAB cannot run the JIT compiler and simplify loops, memory allocation and repeated code calls where appropriate. On every iteration it has to re-evaluate that strings, and figure out what to do with it. This is the complete opposite of efficient.
eval is less efficient to type, because it uses more characters than simply calling functions and operators directly.

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 8 Nov 2015
If you know that there are 14 of them, I would use the eval function (since it doesn’t seem you can avoid it), but instead of creating individual ‘F’ variable column vectors, create one ‘F’ matrix:
for k1 = 1:14
F(:,k1) = eval(sprintf('lok%ddat(1:600,1)', k1));
end
This is UNTESTED CODE! However, it should work.

More Answers (0)

Categories

Find more on Data Type Identification in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!