How to solve issue of "Error using horzcat"?
7 次查看(过去 30 天)
显示 更早的评论
Hi, i have 1 problem as follow:
Error using horzcat
Dimensions of matrices being concatenated are not consistent.
Error in Untitled10 (line 464)
distMatrix(counter,:) = [i,j,dist ];
The code:
counter2 = 1;
for i = allTier2PCH
counter = 1;
distMatrix = zeros(1,3);
for j = allTier1PCH
x1 = node(j).x;
y1 = node(j).y;
x2 = node(i).x;
y2 = node(i).y;
dist = sqrt((x1-x2).^2+(y1-y2).^2);
distMatrix(counter,:) = [i,j,dist ];
counter = counter + 1;
end
end
The i,j and dist value is:
dist = i = 26 j = 4
22.022715545545239
25.000000000000000
How can i solve this problem? I have try some solution, but i could not solve it. Thanks
回答(1 个)
Guillaume
2018-9-27
i and j are scalar, dist is a column vector with 2 elements. As the error message tells you, the dimensions are not consistent. Everything must have the same number of rows.
We have no idea what you intended to do, if you want to replicate i and j for each row of dist:
distMatrix(counter,:) = [repmat([i, j], size(dist, 1), 1), dist];
Or possibly, there's a bug in your code and dist should also be scalar.
2 个评论
Guillaume
2018-9-27
That new error is because the number of rows in distMatrix does not match the number of rows of dist. And indeed you declare distMatrix as a 1 row by 3 column array, whereas you tell us that dist has 2 rows.
There are actually many things wrong with your declaration of distMatrix:
- it is created inside the i loop, so each time you go to the next i, you complete discard what you put in it in the previous step.
- it is declared with just 1 row, but it appears that dist has 2 rows
- it is declared with 3 columns but will ultimately contain at least 7 columns (exactly size(allTier1PCH, 2) columns and if you fix the reset for each i, exactly size(allTier1PCH, 2)^2 columns). This won't cause an error, Matlab will automatically grow the matrix but it is silly to predeclare a matrix the wrong size if you know its ultimate size
Note that if the number of elements in x and y varies per node, your code cannot possibly work (since the number of rows in dist will vary) and you need to rethink your algorithm. So first thing, are x and y always vectors with 2 rows?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!