0

I've written this code :

A is a nXm matrix

[nA, mA] = size(A); currentVector(nA,mA) = 0; for i = 1: nA for j = 1 : mA if A (i,j) ~= 0 currentVector(i,j) = ceil(log10( abs(A(i,j)) )); else currentVector(i,j) = 0; end end end 

How can I write the above code in a more "matlab" way ?

Are there any shortcuts for if/else and for loops ? for example in C :

int a = 0; int b = 10; a = b > 100 ? b : a; 

Those if/else conditions keeps reminding me of C and Java .

Thanks

2 Answers 2

5
%# initialize a matrix of zeros of same size as A currentVector = zeros(size(A)); %# find linear-indices of elements where A is non-zero idx = (A ~= 0); %# fill output matrix at those locations with the corresponding elements from A %# (we apply a formula "ceil(log10(abs(.)))" to those elements then store them) currentVector(idx) = ceil(log10( abs(A(idx)) )); 
Sign up to request clarification or add additional context in comments.

3 Comments

Best solution, but I guess you should put some explanation. ;-)
@kay: done. Feel free to add references to relevant sections in the MATLAB documentation (I'm sure there are plenty discussing writing vectorized code, and performing matrix indexing)
@Amro: Amazing, I'll use that from now on . Thanks!
1
currentVector = ceil(log10(abs(A))); currentVector(A == 0) = 0; 

Note: in Matlab it is totally legal to apply log on zeros - the result is: -inf.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.