フィルターのクリア

Error using horzcat in a for loop

1 回表示 (過去 30 日間)
Sebastian
Sebastian 2014 年 1 月 21 日
コメント済み: Sebastian 2014 年 1 月 21 日
Hi everyone, I am testing a for loop and it is showing me some error in the horzcat, I do not know why it does. Can anyone explain me why it happens, and help me to fix my code. Thank you
p=1;
[row,col] = size(A);
for i = 1:row
for j=1:col
if(A(i,j)>0)
z(p,:)=[j,i];
p=p+1;
end
end
end
B=[(1:p-1)',z]
This is the error:
Error in ==> testloop at 11
B=[(1:p-1)',z]
??? Error using ==> horzcat
CAT arguments dimensions are not consistent.
Error in ==> testloop at 11
B=[(1:p-1)',z];

採用された回答

kjetil87
kjetil87 2014 年 1 月 21 日
編集済み: kjetil87 2014 年 1 月 21 日
horzcat concatinates arrays in horizontal direction i.e x = [a , b] is horzcat. when you call B=[(1:p-1)' ,z] your are calling horzcat (there is also a version called vertcat).
The problem is that (1:p-1)' and z does not have the same amount of rows. Which is strange, because your code looks correct. perhaps z allready existed before you ran the code? try adding
clear z;
before your loop.
or
B=[(1:p-1)' , z(1:p-1,:)];
  1 件のコメント
Sebastian
Sebastian 2014 年 1 月 21 日
It worked, Thank you very much I undestand now why it happens

サインインしてコメントする。

その他の回答 (1 件)

Amit
Amit 2014 年 1 月 21 日
I think I figured it out.
This error must be occurring not everytime. The thing that if you run this few time, the size of z can change. But as you did not cleared the z from previous run, in new case (where size of z should be lower), the new value only replace in the previous locations and does not update the size of z. Try the code below. this will work.
p=1;
[row,col] = size(A);
clear z; % This is needed
for i = 1:row
for j=1:col
if(A(i,j)>0)
z(p,:)=[j,i];
p=p+1;
end
end
end
B=[(1:p-1)',z]
  1 件のコメント
Sebastian
Sebastian 2014 年 1 月 21 日
Both answers were correct, and since you told me this I remember that everytime I open the code the first matrix works, but the second does not. It should be that, Thank you

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeEnvironment and Settings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by