0

I want to run for loop code so it returns different matrices. The below code is what i came up with to better explain it.

for i= 1:(r+1) 
   X_i = projection(data, epsilon)
   U_i = cluster(X_i, number)
   U_con = horzcat(transpose(U_i))
 end

To explain better, I want to run the projection function projection(data, epsilon) r times and it means I would have X_1,X_2,...X_r results( in matrix) and I would also run the cluster function r times to have U_1,...U_r matrices too. and then finally I would find the transpose of each U's and concatenate them together. How can I go about it? Regards.

Jeremiah
  • 324
  • 3
  • 13
  • 5
    You don't want separate variables, as [dynamic variable naming is bad](https://stackoverflow.com/a/32467170/5211833). Use a structure or cells instead, or, if your matrices are of the same size, a multidimensional matrix. – Adriaan Jun 21 '17 at 08:20
  • to elaborate on the above, use `X{i}` and `U{i}` inside the loop. You can build the `U_con` using `horzcat(U_con, U{i})` in each iteration, just need to make sure `U_con` is initialised before (e.g. using `U_con=[]` before the loop). This is not the best way of doing it, but it should work. – Vahe Tshitoyan Jun 21 '17 at 08:38
  • @VaheTshitoyan `horzcat` in a loop is generally very slow, as you basically grow a matrix each iteration. This is slow because each iteration you create a new matrix, copy the content, then delete the old one. Preallocation is the key to solve this time-wise. It is better to use multi-dimensional matrices, or, a cell/structure and concatenate once at the end, to avoid growing matrices every iteration. – Adriaan Jun 21 '17 at 08:53
  • @Adriaan I completely agree, that is why I mentioned at the end that it is not the best way. It is just the fix with the least code modification – Vahe Tshitoyan Jun 21 '17 at 08:56
  • @VaheTshitoyan then it's better to give him a proper solution instead of a quick-and-dirty fix which makes him run into a lot of trouble later on (which coincidentally is usually what happens when people use dynamic variable names) – Adriaan Jun 21 '17 at 08:59
  • @VaheTshitoyan I still do not get how to use it for my case I tried doing it on a smaller case like this: x = [1 2 3 4 5 6 7 8 9 10]; for i= 1:4 X{i} = x end but what I got is not what I am expecting. I have a result of this format X = { [1,1] = 1 2 3 4 5 6 7 8 9 10} – Jeremiah Jun 21 '17 at 09:36

0 Answers0