can't add two matricies of the same size together - matlab

I'm trying to add two matrices together. They are both 400x400. Here's the bit of code that's giving me trouble:
greys = (r+g+b)./3;
fc = cat(3, r, g, b);
combined = (greys+fc)./2; <---error occurs here
But when my code gets to the greys+fc part, it throws an error. This error:
Error using +
Matrix dimensions must agree.
Error in imgSimpleFilter (line 36)
combined = (greys+fc)./2;
when I print the number of rows and columns in both the grey and fc matricies, I get 400 for all of the values (which is exactly as I expected, as I am working with a 400x400 image).
Why isn't it letting me add these together?
I have no problems with the line
greys = (r+g+b)./3;
and that's adding three 400x400 matrices together. Any ideas?

You can't add them because greys is 400x400, while fc is 400x400x3.
Try typing size(greys) and size(fc) on the command line, or whos greys fc to see it.
If you want to "combine" them by averaging them, you could use bsxfun:
combined = bsxfun(#plus, greys, fc) ./ 2;

Related

Noise cancellation with fft failing - unable to assign elements

I have the following code for noise cancellation:
[z,fs] = audioread('noisy_voices.wav'); % Use >>soundsc(z, fs) to hear the unprocessed signal
zproc_vec=zeros(1,length(z));
tail = zeros(1,256);
for k = 0:128:length(z)-256
Z = fft(z(k +1:k + 256).* hann(256));
[zmax, zl] = max(abs(Z(1:128)));
Z(zl-3: zl +3)=0;
Z(256-(zl-3:zl +3)+2)=0;
zproc = ifft(Z);
zproc = zproc+tail;
tail(1:128) = zproc(129:256);
zproc_vec(k+1:k+256)=zproc;
end
soundsc(zproc_vec , fs)
Could anyone tell me why I get this error?
Unable to perform assignments because the left and right sides have a different number of elements
Error in task_one (line 12)
zproc_vec(k+1:k+256)=zproc;
I think the output of your Z = fft( ___ ) line will be a column vector, but you initialise tail to be a row vector with tail = zeros(1,256);
So on this line:
zproc = zproc+tail;
Implicit expansion would make zproc a square 256*256 matrix.
Then your indexing fails, as specified by the error message, because you're trying to assign this square matrix to the 256 elements you're indexing with zproc_vec(k+1:k+256).
Initialising tail to a column vector should solve the issue.
Alternatively you could take the "lazy" way out and make sure you're only operating on column vectors to create zproc
zproc = zproc(:)+tail(:); % Make both terms column vectors for addition
''Unable to perform assignments because the left and right sides have a different number of elements''
What part of the error message do you not understand? It means that the variables on the left and the right side of the equal sign have different sizes so you can't assign the right thingy to the left thingy.
Check the sizes and make sure they are the same.

Index exceeds matrix dimensions

X= [P(1,:,:);
P(2,:,:);
P(3,:,:)];
y= P(4:end,:);
indTrain = randperm(4798);
indTrain = indTrain(1:3838);
trainX= X(indTrain,:);
trainy = y(indTrain);
indTest = 3839:4798;
indTest(indTrain) = [];
testX = X(indTest,:);
testy = y(indTest);
It shows error in trainX= X(indTrain,:); saying
Index exceeds matrix dimensions
can anyone pls clarify ? thanks.
by the way I am having a 4x4798 data which my first 3 rows serve as predictors, and last row (4th row) is my response. how would i correctly split the data into the first 3838 columns as my training set and remaining as testing set.
Thanks..!!
Fix your error
To fix the indexing error you need to select the column indices of X, rather than the row indices:
trainX = X(:, indTrain );
Some words of advice
It seems like your P matrix is 4-by-4798 and it is two dimensional. Therefore, writing P(1,:,:) does select the first row, but it gives the impression as if P is three dimensional because of the extra : at the end. Don't do that. It's bad habit and makes your code harder to read/understand/debug.
X = P(1:3,:); % select all three rows at once
y = P(4,:); % no need for 4:end here - again, gives wrong impression as if you expect more than a single label per x.
Moreover, I do not understand what you are trying to accomplish with indTest(indTrain)=[]? Are you trying to ascertain that the train and test set are mutually exclusive?
This line will most likely cause an error since the size of your test set is 960 and indTrain contains 1:3838 (randomly permuted) so you will get "index exceeds..." error again.
You already defined your indTrain and indTest as mutually exclusive, no need for another operation. If you want to be extra careful you can use setdiff
indTest = setdiff( indTest, indTrain );

Matlab error - Matrix dimensions must agree

cc=imread('<a href=“http://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Pavlovsk_Railing_of_bridge_Yellow_palace_Winter.jpg/250px-Pavlovsk_Railing_of_bridge_Yellow_palace_Winter.jpg”>wintersm.jpg</a>');
c=rgb2gray(cc);
x=ones(256,1)*[1:256];
c2=double(c).*(x/2+50)+(1-double(c)).*x/2;
c3=uint8(255*mat2gray(c2));
t=graythresh(c3);
ct=im2bw(c3,t);
This is a code i have written to threshold the image but cant execute because of the error " ==> times
Matrix dimensions must agree. " . I am new to matlab and i cant figure out how to solve this problem. Please Help.
I looked at the image, it is of size 169x250 . Hence size(c) = [169 250] while size(x) = [256 256]. Since .* operation between c and x needs both of them to be of same size , hence it is giving the error.
Redefine x so that its size matches the size of c
I ran your code but added the following line before c2=double(c).*(x/2+50)+(1-double(c)).*x/2;, I added this:
size(x)
size(c)
and you get the following print out:
ans =
256 256
ans =
169 250
Which is essentially saying, the image isnt the size you think it is and you are mixing your matrix sizes.

Error: Matrix dimensions must agree for plot

having a problem with my "new love", matlab: I wrote a function to calculate an integral using the trapz-method: `
function [L]=bogenlaenge_innen(schwingungen)
R = 1500; %Ablegeradius
OA = 1; %Amplitude
S = schwingungen; %Schwingungszahl
B = 3.175; %Tapebreite
phi = 0:2.*pi./10000:2.*pi;
BL = sqrt((R-B).^2+2.*(R-B).*OA.*sin(S.*phi)+OA.^2.*(sin(S.*phi)).^2+OA.^2.*S.^2.*(cos(S.*phi)).^2);
L = trapz(phi,BL)`
this works fine when i start it with one specific number out of the command-window. Now I want to plot the values of "L" for several S.
I did the following in a new *.m-file:
W = (0:1:1500);
T = bogenlaenge_innen(W);
plot(W,T)
And there it is:
Error using .*
Matrix dimensions must agree.
What is wrong? Is it just a dot somewhere? I am using matlab for the second day now, so please be patient.... ;) Thank you so much in advance!
PS: just ignore the german part of the code, it does not really matter :)
In your code, the arrays S and phi in the expression sin(S.*phi) should have same size or one of them should be a constant in order the code works
The error is most likely because you have made it so that the number of elements in schwingungen, i.e. W in your code, must be equal to the number of elements in phi. Since size(W) gives you a different result from size(0:2.*pi./10000:2.*pi), you get the error.
The way .* works is that is multiplies each corresponding elements of two matrices provided that they either have the same dimensions or that one of them is a scalar. So your code will work when schwingungen is a scalar, but not when it's a vector as chances are it has a different number of elements from the way you hard coded phi.
The simplest course of action (not necessarily the most Matlabesque though) for you is to loop through the different values of S:
W = (0:1:1500);
T = zeros(size(W); %Preallocate for speed)
for ii = 1:length(W)
T(ii) = bogenlaenge_innen(W(ii));
end
plot(W,T)
In your function you define phi as a vector of 10001 elements.
In this same function you do S.*phi, so if S is not the same length as phi, you will get the "dimensions must agree" error.
In your call to the function you are doing it with a vector of length 1501, so there is your error.
Regards

How to use multiple parameters with fittype in Matlab

I have a 1000x2 data file that I'm using for this problem.
I am supposed to fit the data with Acos(wt + phi). t is time, which is the first column in the data file, i.e. the independent variable. I need to find the fit parameters (A, f, and phi) and their uncertainties.
My code is as follows:
%load initial data file
data = load('hw_fit_cos_problem.dat');
t = data(:,1); %1st column is t (time)
x = t;
y = data(:,2); %2nd column is y (signal strength)
%define fitting function
f = fittype('A*cos(w*x + p)','coefficients','A','problem',{'w','p'});
% check fit parameters
coeffs = coeffnames(f);
%fit data
[A] = fit(x,y,f)
disp('confidence interval/errorbars');
ci = confint(A)
which yields 4 different error messages that I don't understand.
Error Messages:
Error using fit>iAssertNumProblemParameters (line 1113)
Missing problem parameters. Specify the values as a cell array with one element for each problem parameter
in the fittype.
Error in fit>iFit (line 198)
iAssertNumProblemParameters( probparams, probnames( model ) );
Error in fit (line 109)
[fitobj, goodness, output, convmsg] = iFit( xdatain, ydatain, fittypeobj, ...
Error in problem2 (line 14)
[A] = fit(x,y,f)
The line of code
f = fittype('A*cos(w*x + p)','coefficients','A','problem',{'w','p'});
specifies A as a "coefficient" in the model, and the values w and p as "problem" parameters.
Thus, the fitting toolbox expects that you will provide some more information about w and p, and then it will vary A. When no further information about w and p was provided to the fitting tool, that resulted in an error.
I am not sure of the goal of this project, or why w and p were designated as problem parameters. However, one simple solution is to allow the toolbox to treat A, w, and p as "coefficients", as follows:
f = fittype('A*cos(w*x + p)','coefficients', {'A', 'w', 'p'});
In this case, the code will not throw an error, and will return 95% confidence intervals on A, w, and p.
I hope that helps.
The straightforward answer to your question is that the error "Missing problem parameters" is generated because you have identified w and p as problem-specific fixed parameters,
but you have not told the fit function what these fixed values are.
You can do this by changing the line
[A] = fit(x,y,f)
to
[A]=fit(x,y,f,'problem',{100,0.1})
which supplies the values w=100 and p=0.1 in the fit. This should resolve the errors you specified (all 4 error messages result from this error)
In general specifying some of the quantities in your fit equation as problem-specific fixed parameters might be a valid thing to do - for example if you have determined them independently and have good reason to believe the values you obtained to be reliable. In this case, you might know the frequency w in this way, but you most probably won't know the phase p, so that should be a fit coefficient.
Hope that helps.