Is This Concatenation Error a Bug?
Show older comments
I have a block of code that processes two vectors t and x that are Nx1 double data types (t and x come from a .mat file and are always equal dimensions and data types). In the routine, I'm trying to concatenate these vectors to create an Nx2 array. I had this block of code working for months in a script, and now that I'm moving it into a function, I'm getting the "dimensions of these arrays are not consistent" error when I try to concatenate!
function [] = YAHBOI(araw,b)
indb = find(b);
yah = araw(indb);
Nyah = length(yah);
boi = {};
for i = 1 : Nyah
boii = yah{i};
file = [boii,'.mat'];
load(file);
boi_rawi = [t, x];
boi = [boi, boi_rawi];
end
end
Error using horzcat
Dimensions of arrays being concatenated are not consistent.
Error in YAHBOI (line 14)
boi_rawi = [t, x];
I'm not new to MATLAB... I know that this should work in theory. In fact, I tried a few workarounds when stepping through the function:
- When I got to the line of interest, I copied and pasted it into the console to see if it would throw an error. It worked, so that's kind of interesting but still expected.
- I tried 1) a second time, but this time I made a quick change to the code:
...
load(file);
y = x;
boi_rawi = [t, y];
...
This change didn't work either.
This seems like a bug to me. Is it? Or am I making some fundamental misunderstanding of how the enviroment works?
Thanks for any assistance!
3 Comments
Stephen23
on 1 Oct 2020
It is possible that one (or more) of those files does not contain the presumed variables, in which case your code will simply use the variable from a previous loop iteration. In the best case this will throw an error, but in the worst case your code will simply continue using incorrect data without any warning. Basically loading directly into the workspace like that is not robust. The robust approach is to always load into an output variable (which is a scalar structure) and access its fields:
boi = cell(1,Nyah);
for k = 1:Nyah
F = sprintf('%s.mat',yah{k});
S = load(file);
boi{k} = [S.t,S.x];
end
I made a few other improvements as well, such as preallocating the cell array before the loop, and using sprintf.
Dan Vergara
on 12 Oct 2020
Answers (1)
Steven Lord
on 1 Oct 2020
1 vote
(t and x come from a .mat file and are always equal dimensions and data types).
Trust but verify. Set an error breakpoint and run your code. When MATLAB stops on that line, verify that what you trust is true actually is.
2 Comments
Dan Vergara
on 12 Oct 2020
Walter Roberson
on 12 Oct 2020
(Me, picturing Steven saying "Trust by verify!" in a fake Russian accent...)
Categories
Find more on Performance and Memory in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!