필터 지우기
필터 지우기

Operations between matrix, different calculation according to conditions.

조회 수: 1 (최근 30일)
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".

채택된 답변

Guillaume
Guillaume 2018년 4월 17일

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
Isai Fernandez
Isai Fernandez 2018년 4월 17일
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 2018년 4월 17일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by