[R] [External] converting MATLAB -> R | element-wise operation

Evan Cooch ev@n@cooch @end|ng |rom gm@||@com
Wed Feb 28 15:11:43 CET 2024


Many thanks for the collective answers -- consider this a thank you to 
the group. I had 'guessed' it had something to do with 'columns then 
rows' or vice versa (MATLAB convention vs R convention), but had never 
heard about 'sweep' before. Most of the time when I run into 'matrix 
orientation' issues, I simply transpose as needed, but that can get 
clunky. 'sweep' has some utility I'll tuck away if needed in future.

Cheers - and thanks again.

On 2/27/2024 4:37 PM, Richard M. Heiberger wrote:
>> t(t(NN)/lambda)
>       [,1]      [,2] [,3]
> [1,]  0.5 0.6666667 0.75
> [2,]  2.0 1.6666667 1.50
> R  matrices are column-based. MATLAB matrices are row-based.
>
>> On Feb 27, 2024, at 14:54, Evan Cooch<evan.cooch using gmail.com>  wrote:
>>
>> So, trying to convert a very long, somewhat technical bit of lin alg
>> MATLAB code to R. Most of it working, but raninto a stumbling block that
>> is probaably simple enough for someone to explain.
>>
>> Basically, trying to 'line up' MATLAB results from an element-wise
>> division of a matrix by a vector with R output.
>>
>> Here is a simplified version of the MATLAB code I'm translating:
>>
>> NN = [1, 2, 3; 4, 5, 6];  % Example matrix
>> lambda = [2, 3, 4];  % Example vector
>> result_matlab = NN ./ lambda;
>>
>> which yields
>>
>>   0.50000   0.66667   0.75000
>>   2.00000   1.66667   1.50000
>>
>>
>> So, the only way I have stumbled onto in R to generate the same results
>> is to use 'sweep'. The following 'works', but I'm hoping someone can
>> explain why I need something as convoluted as this seems (to me, at least).
>>
>> NN <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, byrow = TRUE)  # Example matrix
>> lambda <- c(2, 3, 4)  # Example vector
>> sweep(NN, 2, lambda, "/")
>>
>>
>>       [,1]      [,2] [,3]
>> [1,]  0.5 0.6666667 0.75
>> [2,]  2.0 1.6666667 1.50
>>
>> First tried the more 'obvious' NN/lambda, but that yields 'the wrong
>> answer' (based solely on what I'm trying to accomplish):
>>
>>
>>         [,1] [,2] [,3]
>> [1,] 0.500000  0.5  1.0
>> [2,] 1.333333  2.5  1.5
>>
>> So, why 'sweep'?
>>
>> [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help using r-project.org  mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guidehttp://www.r-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.

	[[alternative HTML version deleted]]



More information about the R-help mailing list