Mustafa Nasser
Mustafa Nasser

Reputation: 271

MATLAB: Creating a matrix from for loop values?

I have the following code:

for i = 1450:9740:89910
    n = i+495;
    range = ['B',num2str(i),':','H',num2str(n)];
    iter  = xlsread('BrokenDisplacements.xlsx' , range);
    displ = iter;
    displ = [displ; iter];
end

Which takes values from an Excel file from a number of ranges I want and outputs them as matricies. However, this code just uses the final value of displ and creates the total matrix from there. I would like to total these outputs (displ) into one large matrix saving values along the way, how would I go about doing this?

Upvotes: 1

Views: 767

Answers (2)

Floris
Floris

Reputation: 46365

Since you know the size of the block of data you are reading, you can make your code much more efficient as follows:

firstVals = 1450:9740:89910;
displ = zeros((firstVals(end) - firstVals(1) + 1 + 496), 7);
for ii = firstVals
    n = ii + 495;
    range = sprintf('B%d:H%d', ii, ii+495);
    displ((ii:ii+495)-firstVals(1)+1,:) = xlsread('BrokenDiplacements.xlsx', range);
end

Couple of points:

  1. I prefer not to use i as a variable since it is built in as sqrt(-1) - if you later execute code that assumes that to be true, you're in trouble
  2. I am not assuming that the last value of ii is 89910 - by first assigning the value to a vector, then finding the last value in the vector, I sidestep that question
  3. I assign all space in iter at once - otherwise, as it grows, Matlab keeps having to move the array around which can slow things down a lot
  4. I used sprintf to generate the string representing the range - I think it's more readable but it's a question of style
  5. I assign the return value of xlsread directly to a block in displ that is the right size

I hope this helps.

Upvotes: 1

Autonomous
Autonomous

Reputation: 9075

How about this:

displ=[];

for i = 1450:9740:89910
    n = i+495;
    range = ['B',num2str(i),':','H',num2str(n)];
    iter  = xlsread('BrokenDisplacements.xlsx' , range);
    displ = [displ; iter];
end

Upvotes: 1

Related Questions