Clear Filters
Clear Filters

Returning Multiple Variables from a function to be added to existing variable.

4 views (last 30 days)
I have a function below that returns multiple variables/matrices seen below. Rather than returning to the variable K_1 i would like to add its contents to an existing variable K. I am unsure how to do this when returning multiple variables and still want to return to the other variables.
[k_1,K_1,B1,b1,c1]=element_stiffness([2,4,1],Coords, v,E,t,D)

Answers (2)

Jan
Jan on 29 Dec 2022
What about:
[k_1,K_1,B1,b1,c1]=element_stiffness([2,4,1],Coords, v,E,t,D)
k = [k, k_1];
% Or:
k = k + k_1;
% Or:
k = zeros(5, 100); % Pre-allocate
for i = 1:5
[k(i, :), K_1,B1,b1,c1]=element_stiffness([2,4,1],Coords, v,E,t,D)
end
  2 Comments
Simon Cook
Simon Cook on 29 Dec 2022
I did consider using a temporary dummy variable as you have demonstarted in the 1st case. However was looking to implement this slightly differently. If just a single variable were returned I imagine something like this (syntax wont run on matlab) but im not sure.
K+=element_stiffness()
Jan
Jan on 30 Dec 2022
If only the first output of the function matters, this is a valid Matlab syntax:
k = k + element_stiffness()

Sign in to comment.


Image Analyst
Image Analyst on 29 Dec 2022
What about
[K(end+1), K_1, B1, b1, c1] = element_stiffness([2,4,1],Coords, v,E,t,D)
This puts the return variable into an element at the end of the K vector. An additional element is created. So if K was [213, 4234] then after calling this if k_1 was 999, the new K would be [213, 4234, 999].
  2 Comments
Simon Cook
Simon Cook on 29 Dec 2022
I think i may have phrased my question poorly rather than concatenating I mean adding the numerical values (in this case K/K_1 is a 10x10 matrix) of the matrix returned from the function to the 10x10 matrix.
K=zeros(10)
%I want to achieve K=K+K_1 however when returning from the function
%This may work but wondered if it could be achieved when directly returning
%from the function
[Temp_variable,A1,B1]=element_stiffness()
K=K+Temp_variable%
%K should now have 1 added to each element. Other variable should be
%returned as normal
function [K_1,A,B]=element_stiffness()
K_1=ones(10)
A=1
B=2
end
Image Analyst
Image Analyst on 30 Dec 2022
Sure, if K_1 and K are 2-D 10x10 matrices, then you can certainly return a temporary variable K_1, and then add that to K like you did.
But you have to do it in MATLAB syntax
K = K + Temp_variable;
not C syntax
K += Temp_variable
The size and shape of Temp_variable has to match that of K of course.

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!