MATLAB: “Matrix dimensions must agree”

dimension matrix

Am trying to do some calculation between two matrix. unfortunately i keep getting this error. Other methods that i have tried such as bsxfun(@times run my computer into space. Any help given will be much appreciated. Here is the line of code
val = load ('edata.txt');
for data=2:1:length(val)-1
if(val(data) > val(data-1) & val(data) > val(data+1) & val(data) > 4)
val1(data) = 1;
else
val1(data) = 0;
end
end
figure
plot((val-min(val))/(max(val)-min(val)), '-g'); title('\bf Prominent Detection Peaks');
hold on
stem(val1'.*((val-min(val))/(max(val)-min(val)))', ':k');
hold off
The of dimension of val1 = 1×7167 and val contain 7168×1 Thanks in advance

Best Answer

Because val1 is not preallocated in the code you've showned, it isn't obvious that is created by the loop.
val1 is shorter by 1 element than val because you explicitly construct it so. Your loop is
for loopindex 2 : numel(val)-1 %data as a name for a loop index is extremely misleading
val1(loopindex) = ...
end %last index is numel(val)-1. Hence val1 has length numel(val)-1
If you want val1 to be the same length as val then you can assign 0 to the last element, the same way 0 is automatically assigned to val1(0) at the first step of the loop when it does val(2) = .... So after the loop you could have:
val1(end + 1) = 0;
But the loop is completely unneeded and is a very slow way to construct val1 (particularly without the aforementioned preallocation). This would achieve the same, including creating val1 the correct length:
valdiff = diff(val);
val1 = [false, valdiff(1:end-1) > 0 & valdiff(2:end) < 0 & val(2:end-1) > 4, false];
With that fix your stem line will work.
No idea why you tried to use bsxfun or why you mentioned it. There is nowhere in your code where it could be used.