简体   繁体   中英

Matlab “Error using vertcat”

I'm trying to make a table in Matlab but I keep getting an error that says "Dimensions of matrices being concatenated are not consistent."

Here's the relevant parts of my code:

x0 = 1.2;
fp = cos(1.2);
fwd = @(x0, h)(sin(x0+h)-sin(x0))./h; %forward differential formula
h1 = @(k)(10.^-k);
h = [h1(1);h1(2);h1(3);h1(4);h1(5);h1(6);h1(7);h1(8);h1(9);h1(10);h1(11);h1(12);h1(13);h1(14);h1(15);h1(16)];
col2 = [abs(fp-fwd(x0,h(1))), abs(fp-fwd(x0,h(2))), abs(fp-fwd(x0,h(3))), abs(fp-fwd(x0,h(4)))
abs(fp-fwd(x0,h(5))), abs(fp-fwd(x0,h(6))), abs(fp-fwd(x0,h(7)))
abs(fp-fwd(x0,h(8))), abs(fp-fwd(x0,h(9))), abs(fp-fwd(x0,h(10)))
abs(fp-fwd(x0,h(11))), abs(fp-fwd(x0,h(12))), abs(fp-fwd(x0,h(13)))
abs(fp-fwd(x0,h(14))), abs(fp-fwd(x0,h(15))), abs(fp-fwd(x0,h(16)))];

The issue is with the first line of col2. Can someone please help here? I've been beating my brains out trying to learn from the mathworks website, but every time I try to format the table a different way I run into new errors. I don't understand why I'm having issues at all since each column will have 16 rows.

If this is the same error you're getting...

Error using vertcat
CAT arguments dimensions are not consistent.

Error in vercatError (line 17)
col2 = [abs(fp-fwd(x0,h(1))), abs(fp-fwd(x0,h(2))), abs(fp-fwd(x0,h(3))),
abs(fp-fwd(x0,h(4)))

...it's only because the last four sets of calls to abs are set on their own lines instead of being part of the assignment to col2 .

The following executes without issue. Make things easier on yourself and vectorize whenever possible!

x0 = 1.2;
fp = cos(1.2);
fwd = @(x0, h)(sin(x0+h)-sin(x0))./h;
h1 = @(k)(10.^-k);
h = h1(1:16)';
col2 = abs(fp-fwd(x0,h));

h =

   0.100000000000000
   0.010000000000000
   0.001000000000000
   0.000100000000000
   0.000010000000000
   0.000001000000000
   0.000000100000000
   0.000000010000000
   0.000000001000000
   0.000000000100000
   0.000000000010000
   0.000000000001000
   0.000000000000100
   0.000000000000010
   0.000000000000001
   0.000000000000000


col2 =

   0.047166759977007
   0.004666195860716
   0.000466079897112
   0.000046602557581
   0.000004660191334
   0.000000465968587
   0.000000046193262
   0.000000000436105
   0.000000055947256
   0.000000166969559
   0.000007938530731
   0.000130063063440
   0.000425048448873
   0.004015843649628
   0.081731455373389
   0.362357754476674

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM