How can I merge 3 matrices into one and skip some variables?

1 Ansicht (letzte 30 Tage)
Iraklis S
Iraklis S am 16 Jan. 2017
Bearbeitet: Stephen23 am 16 Jan. 2017
I have 3 matrices(size 178x1) and I want to merge them into 1 matrix BUT I want to skip rows numbered 48 to 59 and 108 to 130. Seems my code isn't doing the work.
for i=1:178
if i==49
i=60
end
if i==108
i=131
end
Wines=[TotalPhelons(:,i), Flavanoids(:,i), NonflavanoidPhenols(:,i)];
end
What I get is a matrix 178x3. And I get this error :
Index exceeds matrix dimensions. Error in ThirdStep (line 15) Wines=[TotalPhelons(:,i), Flavanoids(:,i), NonflavanoidPhenols(:,i)];
EDIT: I want the new matrix to have 3 collumns (each collumn for each matrix)
  1 Kommentar
Stephen23
Stephen23 am 16 Jan. 2017
Bearbeitet: Stephen23 am 16 Jan. 2017
It is not possible to use that syntax to "skip" loop iterations. If you wish to use a for loop and "skip" iterations then you need to specify this as the for loop input:
for k = [1:47,60:107,131:178]
...
end
Note that this will still not give you what you want, because the output matrix will be indexed at the same rows as the input matrix, and so will be the same size (it will fill the intermediate rows with zeros). You could loop over a separate vector of indices... but really the best solution is to forget about ugly loops and learn to write efficient MATLAB code without loops.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Stephen23
Stephen23 am 16 Jan. 2017
Bearbeitet: Stephen23 am 16 Jan. 2017
Doing this in a loop is very inefficient. You should do this all at once using indexing:
idx = [1:47,60:107,131:178];
out = [TotalPhelons(idx), Flavanoids(idx), NonflavanoidPhenols(idx)]
  2 Kommentare
Iraklis S
Iraklis S am 16 Jan. 2017
Oh thank you very much Stephen!! I'll keep it in mind :)
Iraklis S
Iraklis S am 16 Jan. 2017
I still get an Index exceeds matrix dimensions. error even though I end up with a 178x3 out matrix. Shouldn't I get a matrix with size 144x3??

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by