This question is closed. Reopen it to edit or answer.

1 view (last 30 days)

Show older comments

Hello Friends,

I have the following code:

P = [1, 0, 3];

Q = [0, 4, 5];

AB = [P + Q]; % A vector

CD = [P - Q]; % A vector

EF = [P ./ Q]; % A vector

M = {'AB', 'CD', 'EF'};

for i = 1:length(M)

P1 = P(M{i}~=0); %It removes those elements of P which correspond to 0 entries in M.

t = M{i}; %Create a temporary variable.

M = t(M{i}~=0); %It removes 0 entries from M.

P = P1(~isnan(M(i))); %It removes those elements of P which correspond to NaN entries in M.

M = t(~isnan(M(i))); %It removes NaN entries from M.

if strcmp(M, 'AB')

f = f(P,M);

elseif strcmp(M, 'CD')

f = g(Q,M);

elseif strcmp(M, 'EF')

f = h(R,M);

end

end

This code is not computing P1, t, M, P values properly. For example the following line of code takes M{i} = AB for i = 1, but gives totally wrong answer.

I have tried to change {} to () and [], etc., but nothing works. I will appreciate any advice.

P1 = P(M{i}~=0);

Geoff Hayes
on 18 May 2016

Your line of code has me confused

M = t(M{i}~=0); %It removes 0 entries from M.

The comment says that you are removing zero entries from M. But M has been defined to be a cell array of strings as

M = {'AB', 'CD', 'EF'};

What is the intent of the above assignment? Do you really mean for M to be a cell array of strings, or do you mean it to be a cell array of numbers?

M = {AB, CD, EF};

Also, the line of code

CD = [P*Q]

will generate an error since P and Q do not have the compatible dimensions for matrix multiplication.

Use the debugger to step through the code and you will probably get a good idea as to what is going on. Always look at the variables to verify that they are (with respect to dimension, type, etc.) what you expect them to be.

Geoff Hayes
on 18 May 2016

Todd Leonhardt
on 18 May 2016

I don't understand how that code could even get far enough to attempt to compute P1, etc. It should error out on the 4th line of code where you attempt to compute:

CD = P * Q;

P and Q are both 1 x 3 matrices, so you can not perform matrix multiplication on them as such. You can do any one of the following:

CD = P' * Q; % Take transpose of P, P', so it is a 3 x 1 matrix and results is a 3x3

CD = P * Q'; % Take transpose of Q, Q', so it is a 3 x 1 matrix and result is a 1x1 scalar

CD = P .* Q; % Perform element-wise multiplication so result is a 1 x 3

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

Start Hunting!