"When I run those lines I get the following error but I don't understand why"
That would be because find(vals==0) returns one (or more) index that is greater than size(data, 4). There is nothing in your code that guarantees that it is not the case. As written, it is an implicit assumption of your code that the zeros of values.txt are at indices smaller than the size of that 4th dimension in your nifti file. Obviously, for the two files you're using, this is not the case. There's nothing we can do about that. Either use files where the implicit assumption is true or change what you are doing with these files.