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

조회 수: 1 (최근 30일)
Iraklis S
Iraklis S 2017년 1월 16일
편집: Stephen23 2017년 1월 16일
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
Stephen23
Stephen23 2017년 1월 16일
편집: Stephen23 2017년 1월 16일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2017년 1월 16일
편집: Stephen23 2017년 1월 16일
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
Iraklis S
Iraklis S 2017년 1월 16일
Oh thank you very much Stephen!! I'll keep it in mind :)
Iraklis S
Iraklis S 2017년 1월 16일
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??

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by