0

I am stuck on trying to write the output of a for loop into a vector. The issue is that once it goes through the equation, it stops and spits out this error: "Subscript indices must either be real positive integers or logicals."

I've looked into what this error is and I've checked my code. There are no negative integers being output, nor any zeros. The for-loop, function and the fzero command are all good, if I comment out MW4p(y4,:) = MW4 I get all of my answers on the command window. I just can't put them into an array.

for y4 = linspace(1.4,1.67,100)
x0 = 12;     %Starting Point
fun = @(MW4) (y4.*MW1.*T3)./(y1.*MW4.*T2) - ...
        (((1+((y4+1)./(y4-1)).*p5p2).*((2.*y4)./(y4-1))) ./ ((1+...
        ((y1+1)./(y1-1)).*p5p2).*((2.*y1)./(y1-1)))) .* (((2./(y1-1))...
        ./ (2./(y4-1))).^2); 
MW4 = fzero(fun,x0) 
MW4p(y4,:) = MW4
end

where

y1   = 1.67;
MW1  = 39.55;
T3   = 250;        %k
T2   = 700;        %k
p5p2  = 2.307;     %Determined from T5 desired
MW4p = ones(1,100);

In earlier attempts, I've tried MW4p(y4) = MW4 which had this error: "Attempted to access MW4p(1.4); index must be a positive integer or logical." So I added a colon. Putting this command outside of the for-loop simply had it access the last value of the loop and return the same error.

pm2482
  • 3
  • 2

1 Answers1

0

The error message is telling you exactly what you need to know. y4 is not an integer. When using vectors, matrices, cells, or arrays you can't index with a non-integer number.

vectors, matrices and arrays are discrete structures that can only be indexed with discrete values, though obviously they can be used to store non-discrete values.

Unless I'm missing something, your choices are:

  • Through whatever data structure: store y4 and its corresponding MW4 value as a tuple; for example, you might have an array of structs or cells where one element is y4 and another element is the array returned from MW4
  • Use something like this answer, using a hash map. I haven't looked into this closely, but my guess is you can use a float as the key.
Community
  • 1
  • 1
Brian Vandenberg
  • 4,011
  • 2
  • 37
  • 53
  • Ok, so if i understand this correctly: I can run the for-loop for non-integer iterations and get a stream of answers, OR I can change y4 to a set of integer numbers and have it indexed correctly, even though MW4=fzero(..) might have doubles as answers. – pm2482 Jul 08 '15 at 16:05
  • I modified my answer. – Brian Vandenberg Jul 08 '15 at 17:02