Error when I concatenated matrices

2 ビュー (過去 30 日間)
Viridiana  Torres
Viridiana Torres 2016 年 4 月 27 日
コメント済み: Viridiana Torres 2016 年 4 月 27 日
Hello! does anyone know why when I try to execute this command I got the next error
Error using horzcat
Dimensions of matrices being concatenated are not consistent
Error in @(x)[x,nan(1,max(m)-numel(x))]
where
m=cellfun(@numel,R);
B = cellfun(@(x)[x,nan(1,max(m)-numel(x))],R,'un',0);
where m is 30*1 double and R is 30*1 cell composed by numbers
Thanks a lot!
  3 件のコメント
Muhammad Usman Saleem
Muhammad Usman Saleem 2016 年 4 月 27 日
your matrix are not favorable for multiplication. Read some basics about multiplication of A and B matrix.
Rows of matrix A must be same as columns of matrix B.
Viridiana  Torres
Viridiana Torres 2016 年 4 月 27 日
Thanks muhammad my mistake is not about how to multiplicate A and B, that is something that I know. My mistake is related with how to interpret the codes in Matlab.

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

採用された回答

Stephen23
Stephen23 2016 年 4 月 27 日
編集済み: Stephen23 2016 年 4 月 27 日
This error can occur whenever any of the elements of R are column vectors or matrices:
>> R = {[1;2;3;4],[5;6]};
>> m = cellfun(@numel,R)
m =
4 2
>> B = cellfun(@(x)[x,nan(1,max(m)-numel(x))],R,'un',0)
Error using horzcat
Dimensions of matrices being concatenated are not consistent.
Error in @(x)[x,nan(1,max(m)-numel(x))]
Think about it: you use numel to get the total number of elements in the array and use this to pad the array using a row vector so NaN's, but you always pad using horizontal concatenation [ , ]. But note that numel does not say anything about the orientation of the vectors, or how many rows/columns/pages/... an array has. So you could end up trying to concatenate a column vector and a row vector. Or an array and a row vector.
Basically you are doing this:
>> [[5;6],nan(1,2)]
Error using horzcat
Dimensions of matrices being concatenated are not consistent.
But you need to think about the shape of the two arrays that you are trying to concatenate:
>> [5;6]
ans =
5
6
>> nan(1,2)
ans =
NaN NaN
  1 件のコメント
Viridiana  Torres
Viridiana Torres 2016 年 4 月 27 日
Dear Stephen thanks a lot for your answer and the way you explain it, I really appreciate when someone tries to explain properly its answer. Thanks a lot!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by