Operations between matrix, different calculation according to conditions.

1 view (last 30 days)
I want to multiply two matrices, but depends on conditions I will operate with other expression.
If we name matrices "A" and "B", column matrices, I want to multiply them. I have two operations which I will use according to conditions to proceed.
I tried with this code:
d = [64;
108;
454;
498;
542;
586];
As = [852;
568;
568;
568;
568;
852];
fs = [-344.4991;
-168.8422;
420.0000;
420.0000;
420.0000;
420.0000];
c = 150;
if d<c
Cs(:,1) = (fs-.85*21).*As/1000;
else
Cs(:,1) = (fs).*As/1000;
end
This results in a column matrix "Cs".

Accepted Answer

Guillaume
Guillaume on 17 Apr 2018

if d<c will be true if all elements of d are smaller than c, in which case, all elements of Cs are calculated according to your first formula. Otherwise, the if will be false, and all elements of Cs are calculated according to your second formula. Matlab will not loop for you over the element of d to apply your if element by element.

You could write that loop:

for idx = 1:numel(d)
   if d(idx) < c
      Cs(idx, 1) = ...
   else
      Cs(idx, 1) = ...
   end
end

but that's not the way to do it in matlab. This is much better:

Cs = zeros(size(d));  %preallocate Cs
Cs(d<c) = (420-.85*21).*As(d<c)/1000;   %use logical indexing to assign the required elements
Cs(d>=c) = (420).*As(d>=c)/1000;

Or this is shorter but a bit more obscure:

Cs = (d<c) * ((420-.85*21).*As/1000) + (d>=c) * (420.*As/1000);

For more on logical indexing, see the doc

  2 Comments
Isai Fernandez
Isai Fernandez on 17 Apr 2018
Thanks Guillaume.
I wrote
for idx = 1:numel(d)
if d(idx,1) < c
Cs(idx, 1) = (fs-.85*21).*As/1000;
else
Cs(idx, 1) = fs.*As/1000;
end
end
And I have this, despite of the same sizes of matrices:
Subscripted assignment dimension mismatch.
The same for the second code:
Matrix dimensions must agree.
The idea of the third one works well.
Guillaume
Guillaume on 17 Apr 2018
You must have edited your question. I'm sure there was no fs originally, just a constant 420.
With the loop you need to index all matrices simultaneously, thus
for idx = 1:numel(d)
if d(idx) < c
Cs(idx) = (fs(idx)-.85*21).*As(idx)/1000;
else
Cs(idx) = fs.*As(idx)/1000;
end
end
With the second code, similarly, you've got to apply the logical indexing to all vectors, so
Cs = zeros(size(d)); %preallocate Cs
Cs(d<c) = (fs(d<c)-.85*21).*As(d<c)/1000; %use logical indexing to assign the required elements
Cs(d>=c) = fs(d<c).*As(d>=c)/1000;
Or you can use James' answer that applies the filtering to the only part that is not common between the two expression. It is actually simpler.

Sign in to comment.

More Answers (1)

James Tursa
James Tursa on 17 Apr 2018
Cs(:,1) = (fs-.85*21*(d<c)).*As/1000;

Products

Community Treasure Hunt

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

Start Hunting!