user3129326
user3129326

Reputation: 13

How to execute text made using sprintf as code in MATLAB?

I have some code that does a bunch of fourier transforms on a phone number. Right now I'm cutting the phone number into blocks, but I want it to work for any number of blocks.

The following code is what I want MATLAB to execute, but sprintf only prints it, is there any way to execute this printed text, or should I use a different function instead of sprintf?

output = 'block%d = data(blockstartend(%d, %d):blockstartend(%d, %d));\n';
a2 = [];
for i = 1: j
    a2(1, i) = i;
    a2(2, i) = i;
    a2(3, i) = 1;
    a2(4, i) = i;
    a2(5, i) = 2;
end
a = sprintf(output, a2)

a =

block1 = data123(blockstartend(1, 1):blockstartend(1, 2));
block2 = data123(blockstartend(2, 1):blockstartend(2, 2));
block3 = data123(blockstartend(3, 1):blockstartend(3, 2));
block4 = data123(blockstartend(4, 1):blockstartend(4, 2));
block5 = data123(blockstartend(5, 1):blockstartend(5, 2));
block6 = data123(blockstartend(6, 1):blockstartend(6, 2));
block7 = data123(blockstartend(7, 1):blockstartend(7, 2));
block8 = data123(blockstartend(8, 1):blockstartend(8, 2));
block9 = data123(blockstartend(9, 1):blockstartend(9, 2));
block10 = data123(blockstartend(10, 1):blockstartend(10, 2));

Upvotes: 0

Views: 176

Answers (1)

am304
am304

Reputation: 13886

You probably want to use eval although it's not generally recommended.

Why not do the following instead?

block = cell(10,1);
for k = 1:10
   block{k} = data123(blockstartend(k, 1):blockstartend(k, 2));
end

Upvotes: 4

Related Questions